以下 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];
),并使用创建一个新对象__
函数并连接之间的原型b
, __
, d
和一个实例__
.
这一切背后的原因是什么?
在 ECMAScript 对类的支持成为原生之前,extends 函数会填充预期的继承行为。
如果您习惯了普通的 JavaScript 原型继承,您会想知道为什么它不只是执行__.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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)