javascript 覆盖一个 setter,并且 getter 也必须被覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28950760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:49:22  来源:igfitidea点击:

Override a setter, and the getter must also be overridden

javascriptclassecmascript-6getter-settertraceur

提问by user5321531

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 setmethod of an attribute and it appears the getmethod must be overridden also, otherwise undefinedis returned (i.e., the getmethod is not inherited, uncomment the subclass get property()method above and everything works fine).

覆盖set一个属性的方法,看起来该get方法也必须被覆盖,否则undefined返回(即该get方法未被继承,取消get property()上面的子类方法的注释,一切正常)。

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)?

我认为这是规范的一部分,如果行为是交叉编译的结果,它可能会遵循。可以肯定的是,这是编写覆盖的 setter 和 getter(同时或根本不)的正确方法吗?

采纳答案by Bergi

Yes, this is intentional (a part of the spec). If an object has an own property (.propertyin 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 undefinedwill be returned.

是的,这是故意的(规范的一部分)。如果对象具有自己的属性(.property在您的示例中),则将使用此属性而不是继承的属性。如果该属性存在,但它是一个没有 getter 的访问器属性,undefined则将返回。

Notice that this behaviour has not changed from ES5.

请注意,此行为与 ES5 相比没有改变。