var book = {
_year: 2020, //下划线表示是内部属性,只能通过对象的方法来读写
editor: 1
};
Object.defineProperty(book, 'year', {
get: function () {
return this._year;
},
// 若只指定get方法,不指定set方法,那就默认该属性是只读的
set: function (newYear) {
if (newYear !== this._year) {
this._year = newYear
this.editor++
}
}
});
console.log('未修改的year:' + book.year);//未修改的year:2020
book.year = 2021;
console.log('修改后的year:' + book.year);//修改后的year:2021
console.log('修改year后的editor:' + book.editor);//修改year后的editor:2
js中如何监听一个对象中属性的变化
最新推荐文章于 2024-05-11 13:55:50 发布