Override a setter, and the getter must also be overridden

我怕爱的太早我们不能终老 提交于 2019-11-26 09:58:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!