问题
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 the get
method must be overridden also, otherwise undefined
is returned (i.e., the get
method is not inherited, uncomment the subclass get 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)?
回答1:
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.
来源:https://stackoverflow.com/questions/28950760/override-a-setter-and-the-getter-must-also-be-overridden