views:

298

answers:

4

Hi, I've been watching Douglas Crockford's talks at YUI Theater and I have a question about javascript inheritance...

Douglas gives this example to show that "Hoozit" inherits from "Gizmo":

function Hoozit(id) {
    this.id = id;
}
Hoozit.prototype = new Gizmo();
Hoozit.prototype.test = function (id) {
    return this.id === id;
};

My question is: Why does he writes Hoozit.prototype = new Gizmo() instead of Hoozit.prototype = Gizmo.prototype?

Is there any difference between these two?

Thanks!

+10  A: 

The reason is that using Hoozit.prototype = Gizmo.prototype would mean that modifying Hoozit's prototype object would also modify objects of type Gizmo, which is not expected behavior.

Hoozit.prototype = new Gizmo() inherits from Gizmo, and then leaves Gizmo alone.

Triptych
Thank you so much! :D
Pablo Fernandez
But you can use some indirection (parasitic inheritance) if you want to avoid calling the constructor.
Rob
+1  A: 

If he writes Hoozit.prototype = Gizmo.prototype any modfication he makes later to the prototype of Hoozit will be reflected in the prototype of Gizmo.

Vasil
+1  A: 

In addition to Triptych's answer: Hoozit instances will also inherit all instance properties of Gizmo, not only the ones defined in the prototype; eg:

function Gizmo() {
    this.foo = 'bar'; // foo is visible in every Hoozit instance
}
Christoph
+2  A: 

The above answers address this but if you DO want to inherit the prototype you can use some parasitic magic:

Object.prototype.inherit = function(p) {
    NewObj = function(){};
    NewObj.prototype = p;
    return new NewObj(); 
};

// Paraphrasing of Nicholas Zakas's Prototype Inheritance helper
function inheritPrototype(subType, superType) {
    var prototype = Object.inherit(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
};

Now you can replace the:

Hoozit.prototype = new Gizmo();

with,

Hoozit.prototype = inheritPrototype(Hoozit, Gizmo);

Might not be worth the trouble unless you have a real big Gizmo constructor (the only win in my suggestion is that you don't have to call Gizmo's constructor to hook up the prototype). I have examples of many of these types of patterns here: TDD JavaScript Examples

Rob