以下打字稿代碼:在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
和__
。
這是什麼原因?
也許支持未來的分類? –