Override a setter, and the getter must also be overridden
Yes, this is intentional (a part of the spec). If an object has an own property (.property
in your example), this property will be used and not an inherited one. If that property is existent, but is an accessor property without a getter, then undefined
will be returned.
Notice that this behaviour has not changed from ES5.
user5321531
Updated on December 15, 2020Comments
-
user5321531 over 3 years
class AbstractClass { constructor() { } set property(value) { this.property_ = value; } get property() { return this.property_; } } class Subclass extends AbstractClass { constructor() { super(); } set property(value) { super.property = value; if (!(this.property_ instanceof SubclassAssociatedClass)) throw new TypeError(); } //get property() { // return super.property; //} }
Override the
set
method of an attribute and it appears theget
method must be overridden also, otherwiseundefined
is returned (i.e., theget
method is not inherited, uncomment the subclassget property()
method above and everything works fine).I assume this is a part of the spec., it would follow though possibly if the behaviour was a consequence of cross compiling. Just to be sure, is this the correct way to code overridden setters and getters (both at the same time or not at all)?
-
Bergi about 9 yearsCan you edit your example so that the setter/getter is not just calling super?
-
Admin about 9 yearsThis could be helpful: stackoverflow.com/questions/27400010/…. It discusses the problem in terms of
__defineGetter__
etc., but the principle is the same: if you are defining/redefining the setter on a property that already has a getter, you need to retrieve the getter and reset it along with the setter.
-
-
user5321531 about 9 yearsSwitched to CoffeeScript about the same time as ES5, prior to that
.__defineGetter__()
/ setter was never going to be standardised. -
brianpeiris over 8 years@Bergi Out of curiosity, if you could point to the part of the spec that states this, I'd be grateful. I tried searching both the ES5 and ES6 specs but neither of them seem to explicitly state anything about overriding getters or setters.
-
Bergi over 8 years@brianpeiris: The "overriding" happens in
[[DefineOwnProperty]]
, which is called from literal property definitions or throughObject.defineProperty
(ES5 works basically the same, though the respective spec sections may be easier to read) -
Bergi over 8 years@brianpeiris: And then when evaluating property access or assignment, [[Get]] and [[Set]] are relevant, which both use [[GetOwnPoperty]] that doesn't care whether setter and getter or only one of them is defined.
-
CSchulz almost 6 yearsIs this still correct? Can you please link the spec defining it?
-
Bergi almost 6 years@CSchulz Yes. This hasn't changed since ES6 (linked in the above comments), you'll find the same in the current spec.