要隨時將getter添加到現有對象上,使用Object.defineProperty()函數
const o = { a:0 } Object.defineProperty(o, 'b', { get: function() {return this.a + 1}}); console.log(o.b) // Runs the getter, which yields a + 1(which is 1)
const o = { a: 0 } Object.defineProperty(o, 'b', {set: function(x) { this.a = x/2; }}); o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property console.log (o.a) // 5