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.
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.
Lazy Getter MDN Entry
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
We have to use Object.defineProperty()
as a simple assignment would find the inherited property that has no setter and throws.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With