2017-01-18 161 views
1

我的問題是從this question理解打字稿繼承

啓發這是打字稿繼承代碼

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; 
}; 

,我畫的圖形represantation從here靈感:

enter image description here

您能否確認或更正圖形表示?
我特別不明白這個部分:

function Hook() { this.constructor = Destination; } 

你能告訴我如何繼承與參數工作,並伴有例如

回答

1

它它的任何幫助,我發表過評論的每一行,說明它做什麼,基於當前__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(...);

GitHub上的 - Change Class Inheritance Code

+0

感謝您的回答,你說'指出它的構造函數在subType,以便當一個新的ctor()被創建它實際上創建一個新的subType.'。這點我不清楚。例如,從chrome控制檯輸入 –

+0

:我聲明subType'function subType(){this.a; alert(this.a);}'和ctor'函數ctor(){this.constructor = subType}',但是當我做'new ctor()'時,它不會彈出警報 –

+0

@asdf_enel_hak您還需要鏈原型。僅靠構造函數是不夠的 – series0ne

0

當我合酶我的問題和this answer和@ series0ne的回答

以下是我從打字稿繼承理解:

函數構造函數()的作用:

如鏈接答案:

Car.prototype.constructor = Car; 

它是equivelant

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();