Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
虽然设置了私有属性,但Typescript getter返回未定义_Typescript_Inheritance_Getter Setter - Fatal编程技术网

虽然设置了私有属性,但Typescript getter返回未定义

虽然设置了私有属性,但Typescript getter返回未定义,typescript,inheritance,getter-setter,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;

我用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
为什么会有不同的结果?请注意,如果我注释掉
MyBase
类中的
set prop()
,那么这两个属性都返回
true
,但是这个setter甚至从未执行过,那么它在那里又有什么关系呢


(控制台中的结果)

您不能仅覆盖属性的
集,您正在覆盖整个属性,只需保留
get
未定义即可
get
/
set
语法只是
对象的语法糖。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

Lol如果添加一个setter,getter似乎消失了。您可能无法仅覆盖其中一个。毕竟,get/set指向同一个对象。重写其中一个将重写有关该属性的所有内容。您的链接可以工作,但在我的项目中,
super.prop
会导致编译错误:“只有基类的公共和受保护方法可以通过'super'关键字访问”