定义多个属性
我们可以使用 Object.defineProperties 方法一次定义多个属性:
var book = {};
Object.defineProperties(book, {
__year: {
value: 2014,
writable: true
},
edition: {
value: 1,
writable: true
},
year: {
get: function() {
return this.__year;
},
set: function(newValue) {
if (newValue > 2014) {
this.__year = newValue;
this.edition += newValue - 2014;
}
console.log(this.__year);
}
}
});
book.year = 2017;
console.log(book.edition);
输出结果:
输出结果
网友评论