Bee*_*ice 5 inheritance getter-setter typescript
我已经用 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
Run Code Online (Sandbox Code Playgroud)
为什么会有不同的结果?需要注意的是,如果我注释掉set prop()的MyBase类,那么这两个属性返回true,但是此setter是从来没有执行,所以它为什么重要的是它的存在?
自己运行代码(结果在控制台中)
您不能仅覆盖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
Run Code Online (Sandbox Code Playgroud)