How does the TypeScript extension work?

The following TypeScript code:

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

Generates the following JavaScript code:

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

extendsapparently implemented by a function __extends.

Trying to work out the magic of this feature. I do not understand why we have to copy the properties of the base class in the derived class (that is for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];) and create a new object using the function __and connect between prototypes b, __, dand a copy __.

What is the reason for all this?

+4
source share
2 answers

Until ECMAScript support for classes becomes native, the extends function polifies the expected inheritance behavior.

JavaScript, , __.prototype = b.prototype; . , , for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; , . ...

class BaseClassWithConstructor {
    private _id: number;
    constructor(id: number) {
        this._id = id;
    }

    static doIt() {
        alert('Done it');
    }
}

class DerivedClassWithConstructor extends BaseClassWithConstructor {
    private _name: string;
    constructor(id: number, name: string) {
        this._name = name;
        super(id);
    }
}

DerivedClassWithConstructor.doIt();
0

javascript :

for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];

"" . script

extendStatics(d, b);

extendStatics:

var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };

, [[prototype]], , , .. .


function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __();

prototype of d b. new b(...) - d.instance dummy __, b, , , . . SO.

0

All Articles