Cause:
Recently, when I was looking at the monitoring mechanism of Vue , I encountered the Object.defineProperty method, which is written on MDN as follows:
Object.defineProperty(obj, prop, descriptor)方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。
Since it changes the properties of the object, I don’t see you use it when I write code. Anyway, I usually write it like this:
let obj = {
a: '111',
b: '222'
};
obj.aaa = '333'; // 修改属性
obj.ccc = '444'; // 添加属性
console.log(obj); // {a: "111", b: "222", aaa: "333", ccc: "444"}
Thinking:
What is the difference between the two methods?
Explore:
MDN also said that this method allows precise addition or modification of object attributes. So what about precision?
That's itObject.defineProperty的几个属性了:
configurable
: If and only if the attributetrue
when the attribute descriptordescriptor
to be able to be changed, but also the property to be deleted from the object corresponding to the default .false
enumerable
: If and only if the propertytrue
when the property will appear in the object of enumerated attribute , the default is .false
value
: The value corresponding to the attribute. It can be any valid JavaScript value (number, object, function, etc.), and the default is undefibed .writable
: If and only if the propertytrue
, the value of the property, which is abovevalue
, in order to be the assignment operator changes the default is .false
The main difference:
If you use the assignment operator = assignment, these attributes cannot be set, and the default is:
- Use = to add or delete modified attributes. The default is the attribute displayed during attribute enumeration (you can traverse to it with the for...in or Object.keys method), that is
enumerable 为 true。
- These values can also be changed and deleted, ie
writable 为true
.
Here is a simple little practice:
// 用赋值法创建一个对象
let obj = {
a: '111',
b: '222'
};
// 用赋值法添加一个属性
obj.c = '333';
// 用Object.defineProperty添加一个对象,不可修改,属性不会出现在对象的枚举属性
Object.defineProperty(obj, "d", {
value : '444',
writable : false,
enumerable : false,
configurable : false
});
console.log(Object.keys(obj)); // ["a", "b", "c"],没有d