var book = {
_year: 2004,
edition: 1
};
// 参考网址:
Object.defineProperty(book, "year", {
// writable : false, // 不能重写 book.year 的属性
get: function(){
return this._year;
},
set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
});
book.year = 2005;
console.log(book.edition); //2
// 旧版本支持的语法 - 不能与上面的同时使用,会返回 error
book.__defineGetter__("year", function(){
return this._year;
});
book.__defineSetter__("year", function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
});
book.year = 2005;
console.log(book.edition); //2