JavaScript inheritance extend function

Posted by Zach on Stack Overflow See other posts from Stack Overflow or by Zach
Published on 2010-04-21T20:19:16Z Indexed on 2010/04/21 20:23 UTC
Read the original article Hit count: 201

Filed under:

I'm having some trouble understanding the IF clause at the end of this function from 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;
    }
}

The book explains that these lines ensure that the superclass's constructor attribute is correctly set, even if the superclass is the Object class itself. Yet, if I omit those three lines and do the following:

function SubClass() {};
extend(SubClass, Object);

alert(Object.prototype.constructor == Object);

The alert says 'true', which means the superclass's constructor is set correctly even without those last three lines. Under what conditions, then, does this IF statement do something useful?

Thanks.

© Stack Overflow or respective owner

Related posts about JavaScript