Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Inheritance question

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);

like image 795
bliof Avatar asked Feb 24 '26 12:02

bliof


1 Answers

function extend(subClass, superClass) {

    // create a new empty function
    var F = function() {}; 

    // set the prototype of that function to prototype object of the superclass
    F.prototype = superClass.prototype;

    // now set the prototype of the subClass to a new instance of F
    // this is done so that subClass.prototype.foo = does not affect
    // superClass.prototype.foo
    // if you don't do this, changes to one subClass will affect superClass and all
    // other subClasses of superClass
    subClass.prototype = new F();

Note: subClass.prototype = new superClass() would call the constructor and use the returned new object as the prototype. Which would result in properties on superClass itself would turn up on the prototype chain (since that instance is the prototype object).

    // set the constructor, this indicates that 'subClass' is a function
    subClass.prototype.constructor = subClass;

    // add a property to indicate what the superClass is
    // this way one can call super methods via this.superclass.something
    subClass.superclass = superClass.prototype;

    // in case the superClass was an object...
    if(superClass.prototype.constructor == Object.prototype.constructor) {

       // change the constructor?
       // no idea why they do this here
       // this introduces a side effect to the function
       superClass.prototype.constructor = superClass;
    }
}
like image 76
Ivo Wetzel Avatar answered Feb 27 '26 01:02

Ivo Wetzel