class a {
get b() {
delete this.b;
return this.b = 1;
}
}
var c = {
get b() {
delete this.b;
return this.b = 1;
}
}
console.log(c.b); // works as expected
console.log((new a()).b); // throws error
上面的代码应该可以正常工作,但最后一行会抛出异常。
未捕获的类型错误:无法设置只有 getter(...) 的 # 属性 b
显然,getter 在类中没有被删除,而在对象中却工作得很好。我使用的是最新的稳定版 chrome。
Lazy Getter MDN 条目 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/get#Smart_self-overwriting_lazy_getters
该类的吸气剂坐在.prototype
对象,不在this
,这就是为什么你试图delete
它失败了(而且,正如杰里米指出的那样,它是不可删除的)。
You can however simply create an own property on the instance that shadows the getter:
class a {
get b() {
Object.defineProperty(this, "b", { value: 1, writable: false, configurable: true })
return this.b;
}
}
var c = new a;
console.log(c.b); // 1
我们必须使用Object.defineProperty() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty因为一个简单的赋值会找到没有 setter 和 throws 的继承属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)