I have a question about how Typescript generates javascript code for simple class inheritance. Below is some Typescript code followed by the generated javascript code.
Typescript code:
class Animal {
constructor(public name: string) { }
move(meters: number) {
alert(this.name + " moved " + meters + "m.");
}
}
class Cat extends Animal {
constructor(name: string) { super(name); }
move() {
alert("run...");
super.move(5);
}
}
Generated Javascript code:
var __extends = 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 Animal = (function () {
function Animal(name) {
this.name = name;
}
Animal.prototype.move = function (meters) {
alert(this.name + " moved " + meters + "m.");
};
return Animal;
})();
var Cat = (function (_super) {
__extends(Cat, _super);
function Cat(name) {
_super.call(this, name);
}
Cat.prototype.move = function () {
alert("run...");
_super.prototype.move.call(this, 5);
};
return Cat;
})(Animal);
You will see that the generated javascript code contains an __extends(d, b)
. This function copies all the base class properties to derived class: d[p] = b[p];
.
My question is why is this copying required, just setting the Cat.prototype = _super;
would had been fine and inline with Javascript prototype based inheritance. Copying the the base ctor properties to derived ctor like d[p] = b[p];
seems wastage of memory.