最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Prototypal inheritance in JavaScript - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Feb 14, 2013 at 21:00 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Dec 23, 2008 at 16:45 Pablo FernandezPablo Fernandez 105k58 gold badges195 silver badges234 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 17

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.

The other 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

inheritPrototype(Hoozit, Gizmo);

It 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 in TDD JavaScript Examples.

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.

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
}
发布评论

评论列表(0)

  1. 暂无评论