gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:02:05 25 4
gpt4 key购买 nike

以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com