In JavaScript, the properties of an object are divided into two types: data properties and memory properties:
The difference between the two attributes
We use Object.defineProperty() to first intuitively feel the difference between the two.
The method of setting data properties using Object.defineProperty() is as follows
var obj = {}; Object.defineProperty(obj, "prop", { value: 1, writable: true, //可写性 enumerable: true, //可枚举性 configurable: true //设置该属性是否能被删除,以及enumerable属性是否可以被修改 })
The method of setting memory properties using Object.defineProperty() is as follows
var obj = {}; Object.defineProperty(obj, "prop", { get set enumerable: true, //可枚举性 configurable: true //设置该属性是否能被删除,以及enumerable属性是否可以被修改 })
From the above example, we observe that the memory attribute does not have the two attributes value and writable, but is replaced by the set and get attributes.
Memory Properties
After looking at the intuitive differences between data attributes and memory attributes, let’s take a detailed look at memory attributes, an attribute that is easily overlooked (this is me TT).
The biggest difference between memory attributes and data attributes is the addition of getters/setters, through which the value of the attribute can be operated and some practical functions can be implemented.
//example1 function serialnum() { var n =1; var prop = null; Object.defineProperty(this, "n", { get: function() { return n; }, set: function(value) { if(value > n) n = value; else throw '请输入一个大于n的值'; } }) } var obj = new serialnum(); obj.n = 2; //2 obj.n = 0; //Uncaught 请输入一个大于n的值
In the above example, the set function is used to control the value range of n.
The editor will introduce you to the js data attribute storage attribute here. I hope it will be helpful to you!