var person = {};
Object.defineProperty(person, "name", {
writable: false, // 对象的数据属性不可写-类似常量
value: "Nicholas"
});
console.log(person.name); // Nicholas
person.name = "Michael"; // 重写对象的属性,无效
delete person.name; // 删除也是无效的
console.log(person.name); // Nicholas
var person = {};
Object.defineProperty(person, "name", {
// 不可配置 - 即不能再调用 Object.defineProperty 来修改
configurable: false,
value: "Nicholas"
});
//throws error
Object.defineProperty(person, "name", {
configurable: true,
value: "Nicholas"
});
属性描述符
var book = {};
Object.defineProperties(book, {
_year: {value: 2004},
edition: {value: 1},
year: {
get: function(){
return this._year;
},
set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
}
});
// 获取对象的属性描述符
var descriptor = Object.getOwnPropertyDescriptor(book, "_year");
alert(descriptor.value); //2004
alert(descriptor.configurable); //false
alert(typeof descriptor.get); //"undefined"
var descriptor = Object.getOwnPropertyDescriptor(book, "year");
alert(descriptor.value); //undefined
alert(descriptor.enumerable); //false
alert(typeof descriptor.get); //"function"