覆盖一个 setter,并且 getter 也必须被覆盖 [英] Override a setter, and the getter must also be overridden

查看:39
本文介绍了覆盖一个 setter,并且 getter 也必须被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
    //}

}

重写一个属性的set方法,看起来get方法也必须被重写,否则返回undefined(即get 方法不是继承的,取消注释上面的子类 get 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).

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

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

推荐答案

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

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.

请注意,此行为从 ES5 开始没有改变.

Notice that this behaviour has not changed from ES5.

这篇关于覆盖一个 setter,并且 getter 也必须被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆