Prototypal inheritance in JavaScript

后端 未结 4 1812
不知归路
不知归路 2021-02-03 13:31

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\" i

相关标签:
4条回答
  • 2021-02-03 13:55

    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.

    0 讨论(0)
  • 2021-02-03 13:59

    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.

    0 讨论(0)
  • 2021-02-03 14:03

    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.

    0 讨论(0)
  • 2021-02-03 14:06

    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 讨论(0)
提交回复
热议问题