虽然设置了私有属性,但Typescript getter返回未定义
我用TypeScript 2.6和3.4尝试了以下代码:虽然设置了私有属性,但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;
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'关键字访问”