Javascript – Prototypal inheritance in JavaScript

inheritancejavascriptprototypal-inheritance

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

Why does he write Hoozit.prototype = new Gizmo() instead of Hoozit.prototype = Gizmo.prototype?

Is there any difference between these two?

Best Answer

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.