懒惰的吸气剂在课堂上不起作用 [英] Lazy getter doesn't work in classes
问题描述
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
上面的代码应该可以正常工作,但是最后一行会抛出.
The above code should work fine but the last line throws.
未捕获的TypeError:无法设置仅具有吸气剂(...)的#的属性b
Uncaught TypeError: Cannot set property b of # which has only a getter(…)
很明显,在类中没有删除吸气剂,而在对象中却可以正常工作.我正在使用最新的稳定铬.
Clearly the getter is not being deleted in class whereas it works fine in object. I am on latest stable chrome.
推荐答案
该类的获取器位于.prototype
对象上,而不是在this
上,这就是您尝试delete
失败的原因(并且杰里米指出,它不可删除.
The getter of the class sits on the .prototype
object, not on this
, that's why your attempt to delete
it fails (and, as Jeremy points out, it is not deletable).
不过,您可以简单在遮盖吸气剂的实例上创建自己的属性:
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()
作为一个简单的赋值,将发现没有setter和throws的继承属性.
We have to use Object.defineProperty()
as a simple assignment would find the inherited property that has no setter and throws.
这篇关于懒惰的吸气剂在课堂上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!