Typescript 在TS子类中调用super()的目的是什么?

Typescript 在TS子类中调用super()的目的是什么?,typescript,Typescript,除了让人恼火并使其在父类更新时需要触及每个子类之外…请考虑以下代码: class A { protected sum: number; constructor(protected x: number, protected y: number) { this.sum = this.x + this.y; } } class B extends A { constructor(x: number, y: number) { supe

除了让人恼火并使其在父类更新时需要触及每个子类之外…

请考虑以下代码:

class A {
    protected sum: number;

    constructor(protected x: number, protected y: number) {
        this.sum = this.x + this.y;
    }
}

class B extends A {
    constructor(x: number, y: number) {
        super(x, y);
    }
}
在类
B
的构造函数中调用
super
调用类
A
的构造函数,如果我们查看编译的javascript代码:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
    function A(x, y) {
        this.x = x;
        this.y = y;
        this.sum = this.x + this.y;
    }
    return A;
}());
var B = (function (_super) {
    __extends(B, _super);
    function B(x, y) {
        _super.call(this, x, y);
    }
    return B;
}(A));
我们这样做的原因应该很清楚,否则在
A
中发生的所有事情都不会发生,即成员
x
y
sum
不会被分配到类
B
的实例中

然后,您可能会问“好吧,好吧,但是为什么这不会自动发生?为什么编译器不能为我调用
super

这是一个公平的问题,我可以想到两个主要原因:

(1) 因为有时您想在调用
super
之前做一些事情,例如:

class A {
    protected sum: number;

    constructor(protected x: number, protected y: number) {
        this.sum = this.x + this.y;
    }
}

class B extends A {
    constructor(x: number, y: number) {
        if (x % 2 === 0) {
            super(x, y);
        } else {
            super(x + 1, y);
        }
    }
}
您必须先调用
super
,然后才能在
B
的ctor中访问
this

(2) 它清楚地表明这就是正在发生的事情,否则你可能不会期望它发生,因为你看不到它


此要求仅对构造函数有效,类方法不需要调用它们的super,但是如果您想执行父方法功能,您可以自由地这样做。

这很有意义。但是像_preconstruct()这样的方法不能存在于执行这些子类的前置超函数的地方吗?似乎比强制每个子类复制其父类的条件更好。我不确定我是否理解您的建议与当前的
super
做事方式之间的区别。我认为@user3583223可能建议使用
\u preconstruct()
函数只能用于调用
super()
时需要一些逻辑的子类。所有不需要任何特殊逻辑的子类都可以隐式调用
super()
。换句话说,
\u preconstruct()
将是完全可选的,而对
super()
的调用则不是可选的。@MadScone我想那会更令人困惑,什么时候调用这个
\u preconstruct()
?在家长面前?在那之后?介于两者之间?这个
super()
可能太明确了,但很明显是怎么回事,我不同意,只是用@user3583223的意思来澄清一下。