理解打字稿继承

时间:2017-01-18 10:27:55

标签: javascript inheritance typescript

我的问题来自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;
};

我从here启发了图形再现:

enter image description here

您能否确认或更正ghaphical表示? 我特别不明白这一部分:

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

你能告诉我继承如何使用参数和附带的例子

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

当我合成我的问题并this answer和@ series0ne的回答

以下是我从typescript继承中理解的内容:

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