Introduction to the
Property descriptors are the contents of JS objects
Property descriptors include data descriptors and access descriptors.
Access descriptor effects
The assignment of an object attribute can be handled by the set and get methods, which can qualify the value passed in. For example, age cannot be a negative number
This is how we implement computed properties in the Vue framework, and how we dynamically change the UI in DOM operations by changing the value of properties like innerHtml
Access descriptor example
DefineProperty is a static method on Object that uses:
Object.defineProperty(obj, prop, descriptor)
Copy the code
parameter
Obj Specifies the object for which attributes are to be defined. Prop The name of the property to be defined or modified, or the property descriptor to be defined or modifiedCopy the code
Matters needing attention:
Do not mention object attributes defined using property descriptors in get and set methods, otherwise you will get into infinite recursion and full stack error. Values can be passed through an intermediate variable
function Demo(x) {
var _x = x// The intermediate variable, _x, is initialized to the value in x
Object.defineProperty(this.'x', {
get: function () {// the get method fetches the contents of _x equivalent to the contents of x
console.log("get")
return _x
},
set: function (x) {The set method updates the _x content. Use the get method again, taking the _x intermediate variable as usual
if(x>100){
x = 100
}
if(x<0){
x = 0
}
_x = x
console.log("set")}})this.x = _x
}
var obj = new Demo(50)
Copy the code
descriptor
The key values that the descriptor can have
configurable | enumerable | value | writable | get | set | |
---|---|---|---|---|---|---|
Data descriptor | can | can | can | can | Can not be | Can not be |
Access descriptor | can | can | Can not be | Can not be | can | can |
Data descriptors are available for value and writable without the use of get and set methods. Once used, they become access descriptors, and value and writable are invalid
enumerable
- Controls whether a property can be traversed by forin, forof if it is false
- Some properties on the prototype chain are seen in the console, but not iterated, because they were manipulated to false
- Through Object. The obtained getOwnPropertyDescriptor to descriptor cannot directly through the Object. Enumerable = Boolean value way to effective configuration (although it is true that the value of the)
example
var student = {
dag:"awe".name:"zhangsan".age:19,}var x = Object.getOwnPropertyDescriptor(student,"name")
// x.enumerable = false is invalid and still traversable
Object.defineProperty(student,"name", {// The name cannot be traversed
enumerable:false
})
Copy the code