参考链接1: javascript学习(九)对象属性的特性
参考链接2:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
案例1:
var person = {};
Object.defineProperty(person, "name", {
value:"Tom",
writable:false,
enumerable:false,
configurable:false
});
console.log(person.name); //Tom
person.name = "Linda";
console.log(person.name); //Tom
案例2:
var person = {};
Object.defineProperty(person, "name", {
value:"Tom",
writable:true,
enumerable:false,
configurable:true
});
console.log(person.name); //Tom
person.name = "Linda";
console.log(person.name); //Linda
图解:
案例3:官方文档解释的太好了!!!
Writable attribute
When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.
var o = {}; // Creates a new object
Object.defineProperty(o, 'a', {
value: 37,
writable: false
});
console.log(o.a); // logs 37
o.a = 25; // No error thrown
// (it would throw in strict mode,
// even if the value had been the same)
console.log(o.a); // logs 37. The assignment didn't work.
As seen in the example, trying to write into the non-writable property doesn’t change it but doesn’t throw an error either.
以上内容作为个人学习记录使用,仅供参考,不足之处,烦请告知。