1

I think they are equivalent but I'm not sure:

var __extends = function(child, parent) { 
    for (var key in parent) { 
        if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    }
    function ctor() { 
        this.constructor = child; 
    } 
    ctor.prototype = parent.prototype; 
    child.prototype = new ctor; 
    child.__super__ = parent.prototype;
    return child; 
};

And

var __extends = function(child, parent) { 
    for (var key in parent) { 
        if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    }
    child.prototype = parent.prototype;
    child.prototype.constructor = child;
    child.__super__ = parent.prototype;
    return child; 
};
armen.shimoon
  • 6,303
  • 24
  • 32

1 Answers1

1

Both functions extend the child (function) object with all properties of the parent object, and they set the __super__ property. Then the differences begin:

function ctor() { 
    this.constructor = child; 
} 
ctor.prototype = parent.prototype; 
child.prototype = new ctor;

This code creates a prototype object for child which inherits from parent.prototype. It is an old version of what Object.create() does. This is the classical JavaScript inheritance pattern.

child.prototype = parent.prototype;
child.prototype.constructor = child;
child.__super__ = parent.prototype;

This code is crap. It sets the child's prototype object to parent.prototype, but forgets right in the next line that now both properties point to the same object (child.prototype === parent.prototype). Therefore, parent.prototype.constructor === child and child.__super__ === child.protoype - urgh.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375