2017-01-18 118 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();