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;
}
}
}
});
book.year = 2006;
alert(book.year); // 2004
alert(book.edition); // 1

为什么alert
显示旧的属性值,即使setter应该更新属性?
答案 0 :(得分:2)
使properties可写为可写的默认值为false
var book = {};
Object.defineProperties(book, {
_year: {
value: 2004,
writable: true
},
edition: {
value: 1,
writable: true
},
year: {
get: function() {
return this._year;
},
set: function(newValue) {
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
}
});
book.year = 2006;
alert(book.year);
alert(book.edition);