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

查看:526
本文介绍了覆盖一个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).

我认为这是规范的一部分,它会跟随,虽然可能如果行为是交叉编译的结果。

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

是的,这是故意的(规范的一部分)。如果一个对象有自己的属性(在你的示例中 .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天全站免登陆