当我在父类中声明getter,并在子类中声明setter时,子类中的getter返回undefined。我想这种行为有利于编译的javascript规则。在其他语言(例如actionscript)中,您可以在不同的类中定义setter和getter,并且一切都按预期工作。在打字稿中,我们没有打字稿编译器的警告,这是非常危险的。这种行为的原因是什么?
class ImmutableVector {
_x: number;
_y: number;
constructor(x: number = 0, y: number = 0) {
this._x = x;
this._y = y;
}
public get x(): number {
return this._x;
}
public get y(): number {
return this._y;
}
}
class Vector extends ImmutableVector {
constructor(x: number = 0, y: number = 0) {
super(x, y);
}
public set x(x: number) {
this._x = x;
}
public set y(y: number) {
this._y = y;
}
}
export default function test() {
var immutable = new ImmutableVector(100, 100);
console.log(immutable.x); // output: 100
var mutable = new Vector(200, 200);
console.log(mutable.x); // output: undefined
}