代码之家  ›  专栏  ›  技术社区  ›  pistacchio

Javascript:原型内在和超级构造函数

  •  4
  • pistacchio  · 技术社区  · 16 年前

    如何从继承对象调用超级构造函数?例如,我有一个简单的动物类:

    function Animal(legs) {
      this.legs = legs;
    }
    

    function Chimera(maxLegs) {
        // generate [randLegs] maxed to maxLegs
        // call Animal's constructor with [randLegs]
    }
    Chimera.prototype = new Animal;
    Chimera.prototype.constructor = Chimera;
    

    如何调用动物的构造器?谢谢

    3 回复  |  直到 16 年前
        1
  •  4
  •   gblazex    16 年前

    我觉得你想要的和 constructor chaining :

    function Chimera(maxLegs) {
        // generate [randLegs] maxed to maxLegs
        // call Animal's constructor with [randLegs]
        Animal.call(this, randLegs);
    }
    

    Parasitic Inheritance

    function Chimera(maxLegs) {
    
        // generate [randLegs] maxed to maxLegs
        // ...
    
        // call Animal's constructor with [randLegs]
        var that = new Animal(randLegs);
    
        // add new properties and methods to that
        // ...
    
        return that;
    }
    
        2
  •  2
  •   sth    16 年前

    你可以使用 call

    function Chimera(maxLegs) {
       var randLegs = ...;
       Animal.call(this, randLegs);
    }
    
        3
  •  -2
  •   kevin628 Padmapriya Vishnuvardhan    16 年前

    你应该能够做到:

    new Animal();
    
    推荐文章