[英]understanding typescript inheritance
我的問題靈感來自這個問題
這是打字稿繼承代碼
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 __();
};
我將版本簡化為這個版本
function extend(Destination, Base) {
function Hook() { this.constructor = Destination; }
Hook.prototype = Base.prototype;
var hook = new Hook();
Destination.prototype = hook;
};
我從這里繪制了圖形表示:
你能確認或更正圖形表示嗎?
我特別不明白這部分:
function Hook() { this.constructor = Destination; }
你能告訴我繼承是如何處理參數和附帶的例子的嗎
這是任何幫助,我已經根據當前的__extends
函數注釋了每一行以說明它的作用(它與您的示例略有不同)
var extend = function (subType, superType) {
// Copy superType's own (static) properties to subType
for (var property in superType) {
if (superType.hasOwnProperty(property)) {
subType[p] = superType[p];
}
}
// Create a constructor function and point its constructor at the subType so that when a new ctor() is created, it actually creates a new subType.
function ctor() {
this.constructor = subType;
}
if(superType === null) {
// Set the subType's prototype to a blank object.
subType.prototype = Object.create(superType);
} else {
// set the ctor's prototype to the superType's prototype (prototype chaining)
ctor.prototype = superType.prototype;
// set the subType's prototype to a new instance of ctor (which has a prototype of the superType, and whos constructor will return a new instance of the subType)
subType.prototype = new ctor();
}
};
請注意, __extends
可能會在不久的將來再次更改以包含Object.setPrototypeOf(...);
的使用Object.setPrototypeOf(...);
GitHub -更改類繼承代碼
當我綜合我的問題和這個答案以及@series0ne 的答案時
這是我從打字稿繼承中了解到的:
函數 ctor() 的作用是:
如鏈接的答案:
Car.prototype.constructor = Car;
它是等價的
subType.prototype.constructor = subType
它提供:
subType.constructor === subType -> true
為了
ctor.prototype = superType.prototype;
subType.prototype = new ctor();
它是等價的
Car.prototype = new Vehicle(true, true);
這確保
subType.prototype = new superType();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.