Reputation: 7650
My question is inspired from this question
This is typescript inheritance 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 __();
};
and I simplified version to this version
function extend(Destination, Base) {
function Hook() { this.constructor = Destination; }
Hook.prototype = Base.prototype;
var hook = new Hook();
Destination.prototype = hook;
};
and I draw graphical represantation inspired from here:
Could you confirm or correct ghaphical representation?
I especially did not understand this part:
function Hook() { this.constructor = Destination; }
And could you tell me how inheritance work with arguments and accompanied example
Upvotes: 1
Views: 241
Reputation: 7650
When I synthase my question and this answer and @series0ne's answer
Here is what I understand from typescript inheritance:
function ctor() does:
As in the linked answer:
Car.prototype.constructor = Car;
it is equivelant
subType.prototype.constructor = subType
which provides:
subType.constructor === subType -> true
for
ctor.prototype = superType.prototype;
subType.prototype = new ctor();
it is equivalent
Car.prototype = new Vehicle(true, true);
which ensures
subType.prototype = new superType();
Upvotes: 0
Reputation: 42380
It it's any help, I've commented each line to illustrate what it does, based on the current __extends
function (it's changed slightly from your example)
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();
}
};
Note that __extends
may change again in the very near future to include the use of Object.setPrototypeOf(...);
GitHub - Change Class Inheritance Code
Upvotes: 1