对象中的 defineProperty 和 defineProperties 属性
var obj = {
name: "KingMan"
}
// 属性类型
console.log('---------------数据属性---------------');
// 1.数据属性
// writable
var person = {};
Object.defineProperty(person,"name",{
writable:false, //能否修改属性值(默认true)
value:"Whiskey" //属性数据值(默认undefined)
});
console.info(person.name);
person.name="Tequila";
console.info(person.name);
// configurable
var person1 = {};
Object.defineProperty(person1,"name",{
configurable:false, //能否删除属性值(默认true)
value:"Vodka"
});
console.info(person1.name);
delete person.name;
console.info(person1.name);
// 定义配置后无法修改回(除writable外)
try {
Object.defineProperty(person1,"name",{
configurable:true, //能否删除属性值
value:"Vodka"
});
} catch (error) {
console.error(error);
}
// enumerable
var person2 = {
age: 12
};
Object.defineProperty(person2,"name",{
enumerable:false, //能否通过for-in循环出来属性(默认true)
value:"Vodka"
});
for(item in person2){
console.info(item)
}
console.log('---------------访问器属性---------------');
// 2.访问器属性
var book = {
_year: 2004,
edition: 1
}
console.info(book)
Object.defineProperty(book, "year", {
get: function () {
return this._year
},
set: function (val) {
if(val > this._year){
this.edition += val - this._year;
this._year = val;
}
}
})
book.year = 2006;
console.info(book.edition);
console.info(book.year);
console.log('---------------定义多个属性---------------');
var fruit = {};
Object.defineProperties(fruit,{
_quality: {
value: 100
},
star: {
writable:true, //注意:不再是默认可修改,需要添加可修改属性
value: 20
},
quality: {
get: function () {
return this._quality
},
set: function (newVal) {
this.star = this._quality / newVal
}
}
})
console.info(fruit.star)
fruit.quality = 4
console.info(fruit.star)
在红皮书上看到的是这样的:
如果没有设置writable属性,并不能修改定义的属性值