【发布时间】:2015-11-19 01:49:55
【问题描述】:
以下 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 和__ 的一个实例。
这一切背后的原因是什么?
【问题讨论】:
-
也许是为了支持未来的分类?
标签: javascript typescript