javascript - TypeScript 中的扩展如何工作?

标签 javascript typescript

以下 TypeScript 代码:

class BaseClassWithConstructor {
    private _id: number;
    constructor(id: number) {
        this._id = id;
    }
}

class DerivedClassWithConstructor extends BaseClassWithConstructor {
    private _name: string;
    constructor(id: number, name: string) {
        this._name = name;
        super(id);
    }
}

生成以下 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; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var BaseClassWithConstructor = (function () {
    function BaseClassWithConstructor(id) {
        this._id = id;
    }
    return BaseClassWithConstructor;
})();
var DerivedClassWithConstructor = (function (_super) {
    __extends(DerivedClassWithConstructor, _super);
    function DerivedClassWithConstructor(id, name) {
        this._name = name;
        _super.call(this, id);
    }
    return DerivedClassWithConstructor;
})(BaseClassWithConstructor);

extends 似乎是由__extends 函数实现的。

正在尝试找出这个函数背后的魔力。我不明白为什么 我们必须将基类中的属性复制到派生类(即 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];),并使用 __ 函数创建一个新对象,并将原型(prototype)连接到 b__d__ 的实例。

这一切背后的原因是什么?

最佳答案

在 ECMAScript 原生支持类之前,extends 函数会填充预期的继承行为。

如果您习惯了普通的 JavaScript 原型(prototype)继承,您会想知道为什么它不只是执行 __.prototype = b.prototype; 部分。如果是这样,您将有兴趣知道添加 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; 意味着静态成员也将被复制。例如……

class BaseClassWithConstructor {
    private _id: number;
    constructor(id: number) {
        this._id = id;
    }

    static doIt() {
        alert('Done it');
    }
}

class DerivedClassWithConstructor extends BaseClassWithConstructor {
    private _name: string;
    constructor(id: number, name: string) {
        this._name = name;
        super(id);
    }
}

DerivedClassWithConstructor.doIt();

关于javascript - TypeScript 中的扩展如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32202625/

相关文章:

typescript - Next.js typescript 使用 babel-plugin-module-resolver 导入别名

javascript - vuejs - .bind(this) 没有按预期工作

javascript - 存储从外部摄像头拍摄的图像并将其存储在数据库中 - Ionic 3

angular - IE11 上的 Webpack + Angular(4) + ES6 无法正常工作

javascript - 使用数据 URI 将多个文件下载到一个 Zip 文件中

typescript - 将 gulp 与 tsify 和 babelify 一起使用不会运行 babel

javascript - 将对象值转换为大写

javascript - Reactjs 将动态组件添加到其他组件中

javascript - 使用 SAS key 直接从客户端上传到 Azure 存储

javascript - 显示子项时动态更改容器背景