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

use*_*223 10 typescript

除了令人烦恼并使其更新以便在更新父类时需要触及每个子类...

Nit*_*mer 8

请考虑以下代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

要将呼叫super在类的构造函数B调用类的构造函数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));
Run Code Online (Sandbox Code Playgroud)

应该清楚为什么我们这样做,因为否则在ctor中发生的一切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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您必须调用super您访问之前this在的构造函数B.

(2)它明确表示这是正在发生的事情,否则你可能不会指望它发生,因为你没有看到它.

此要求仅对构造函数有效,类方法不需要调用它们的超级,但如果要执行父方法功能,则可以自由地执行此操作.