In JavaScript, the attributes of an object are divided into data properties and memory properties:
The difference between two types of attributes
We use Object.defineproperty () first to intuitively feel the difference between the two.
The method for setting data properties using Object.defineproperty () is as follows
var obj = {};
Object.defineproperty (obj, "prop", {
value:1,
writable:true,//writable
enumerable:true,/
/enumerable Configurable:true//Set whether the property can be deleted, and whether the enumerable property can be modified
})
Use Object.defineproperty () to set the storage properties as follows
var obj = {};
Object.defineproperty (obj, "prop", {
get
set
enumerable:true,//enumerable
Configurable:true// Set whether this property can be deleted, and whether the enumerable property can be modified
}
From the above example, we observed that the memory properties did not have the value and writable two attributes, and instead set and get properties.
Memory properties
After reading the visual differences between the data attributes and the memory properties, let's look at the properties of the memory properties that are easily overlooked (that is, I TT).
The biggest difference between the memory attribute and the data attribute is the addition of getter/setter, which can manipulate the value of the property and realize some practical functions.
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 ' Please enter a value greater than n ';
}}} var obj = new Serialnum ();
OBJ.N = 2;
2
OBJ.N = 0;
Uncaught Please enter a value greater than n
In the example above, the SET function is used to control the value range of N.
About JS data attribute storage Properties Small series on the introduction here, I hope to help you!