看例子:
var o = {
a: 7,
get b() {
return this.a + 1;
},
set c(x) {
this.a = x / 2
}
};
console.log(o.a); // 7
console.log(o.b); // 8
o.c = 50;
console.log(o.a); // 25
使用 Object.defineProperty()
var d = Date.prototype;
Object.defineProperty(d, 'year', {
get: function() { return this.getFullYear(); },
set: function(y) { this.setFullYear(y); }
});
使用 Object.defineProperties()
var o = { a: 0 };
Object.defineProperties(o, {
'b': { get: function() { return this.a + 1; } },
'c': { set: function(x) { this.a = x / 2; } }
});
网友评论