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);
extends
seems to be implemented by the __extends
function.
Being trying to work out the magic behind this function. I don't understand why
we have to copy properties in the base class to the derived class (i.e. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
), and create a new object using the __
function and hook up the prototypes between the b
, __
, d
and an instance of __
.
What is the reasoning behind all this?