let book = {
// 对象里面的属性实则可以被直接访问
year_: 2017,
edition: 1
};
准备以上对象,通过访问器属性间接修改对象里面属性的值
es5的用法:
// es5
Object.defineProperty(book, "year", {
get() {
return this.year_;
},
set(newValue) {
if (newValue > 2017) {
this.year_ = newValue;
this.edition += newValue - 2017;
}
}
});
console.log(book.year_, book.edition);//2017 1
book.year = 2018;
console.log(book.year_, book.edition);//2018 2
es5之前的用法
book.__defineGetter__("year", function () {
return this.year_;
});
book.__defineSetter__("year", function (newValue) {
this.year_ = newValue;
this.edition += newValue - 2017;
});
console.log(book.year_, book.edition);//2017 1
book.year = 2018;
console.log(book.year_, book.edition);//2018 2