While playing around with the online TypeScript compiler, I've noticed that the creators chose to implement inheritance with the help of the following method (which I have made somewhat more readable):
var __extends = function(type, base) {
for (var prop in base) { // why copy the properties?
if (base.hasOwnProperty(prop)) {
type[prop] = base[prop];
}
}
function __() { // <- ?
this.constructor = type;
}
__.prototype = base.prototype.
type.prototype = new __();
};
The method is then used in the following manner:
var Item = (function () {
function Item() {
}
return Item;
})();
var Sword = (function (base) {
__extends (Sword, base);
function Sword() {
base.call(this);
}
return Sword;
})(Item);
I have a hard time understandind the implementation of the __extends
method.
What is the purpose of manually copying all the properties from the extending type? Won't inheriting the prototype take care of that?
Is there a performance penalty when searching for properties in the prototype tree as opposed to directly copied properties?
The second part I also can't understand the purpose of. Instead of doing this:
function __() {
this.constructor = type;
}
__.prototype = base.prototype.
type.prototype = new __();
Couldn't this simply be implemented as:
type.prototype = base.prototype;