时间:2021-02-22 09:55:00 来源:互联网 热度: 作者: 佚名 字体:
要随时将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
发布此文章仅为传递网友分享,不代表本站观点,若侵权请联系我们删除,本站将不对此承担任何责任。