尽管已设置私有属性,但Typescript getter返回未定义

时间:2019-06-13 20:47:45

标签: typescript inheritance getter-setter

我已经使用TypeScript 2.6和3.4尝试了以下代码:

abstract class Base {
    private _prop = false;
    public get prop() { return this._prop; }
    public setProp(v) { this._prop = v; }

    private _otherProp = false;
    public get otherProp() { return this._otherProp; }
    public set otherProp(v) { this.setOtherProp(v); }    
    public setOtherProp(v) { this._otherProp = v; }
}

class MyBase extends Base {
    public set prop(v) { this.setProp(v); }
}

const base = new MyBase();

base.setProp(true);
base.setOtherProp(true);

console.log(`prop = ${base.prop}`); // prop = undefined
console.log(`otherProp = ${base.otherProp}`); // otherProp = true

为什么结果不同?请注意,如果我将set prop()类中的MyBase注释掉,则两个属性都返回true,但是此setter甚至都不会执行,所以为什么它存在在那里很重要?

Run the code yourself(控制台中的结果)

1 个答案:

答案 0 :(得分:0)

您不能仅覆盖属性的set,而是要覆盖整个属性,只是您保留get未定义。 get / set语法只是Object.defineProperty的语法糖,它覆盖了整个属性。

覆盖get,然后调用super.prop,所有操作均按预期进行:

abstract class Base {
    private _prop = false;
    public get prop() { return this._prop; }
    public setProp(v: boolean) { this._prop = v; }

    private _otherProp = false;
    public get otherProp() { return this._otherProp; }
    public set otherProp(v) { this.setOtherProp(v); }    
    public setOtherProp(v: boolean) { this._otherProp = v; }
}

class MyBase extends Base {

    public get prop() { return super.prop; }
    public set prop(v: boolean) { this.setProp(v); }
}

const base = new MyBase();

base.setProp(true);
base.setOtherProp(true);

console.log(`prop = ${base.prop}`); // prop = true
console.log(`otherProp = ${base.otherProp}`); // otherProp = true

Playground link