This is the extend function from the book “Pro JavaScript Design Patterns”
function extend(subClass, superClass) {
var F = function() {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if(superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
I have problems with the first 3 lines… It creates an empty function and then it sets the F.prototype to superClass.prototype which means (for 2 new constructor functions e.g. foo, bar and foo extends bar) that F.prototype will have a constructor property: bar and proto :Object, or not?
And on line 3: subClass.prototype = new F(); happens something that I cannot understand.. Why the inheritance happens here when F’s [[Prototype]] is Object?
What are the differences between the first 3 lines and
subClass.prototype = new superClass();
when the code executes? I mean how The first does the same as the second one.
Just to add there is a call to the superClass constructor in the subClass.
The call is “className”.superclass.constructor.call(this);
We’ve got constructors:
F,Super&Sub.We’ve got objects
f,super, &subthat are made using said constructors.i.e.
f = new F,super = new Super,sub = new SubWe know
f.__proto__ === super.__proto__ === Super.prototypefrom line 2From line 3 we can see that
sub.__proto__ === f&sub.__proto__.__proto__ === Super.prototypeAlso we have
Sub.superClass === Super.prototypefrom line 5.and from line 4 & 6 we can say that
sub.constructor === Sub&super.constructor === SuperThe reason we can call
new Fbefore on line 3 before line 7 is because line 7 set’sf.__proto__.constructor === Superwhere asf.constructoris alreadySub. basically line 7 is cleaningSuperup and shouldn’t effectSubat all because you should never call.__proto__.constructorin real code.This particular function explicity does not call
Superas function but only make’s sure that objects constructed throughSubhaveSuper.prototypein their chain.