【问题标题】:How to get a constructor function to inherit from a constructor function in Javascript?如何让构造函数继承自Javascript中的构造函数?
【发布时间】:2023-03-07 08:25:01
【问题描述】:

所以我正在学习 Javascript 及其所有的原型优点,但我对以下问题感到困惑:

说我有这个

var Animal = function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){
   this.a = a;
   this.b = b;
   //...etc...
};

var x = new Animal(1,2,3....);

现在如何创建一个继承自 Animal 构造函数的 Cat 构造函数,这样我就不必再次输入超长参数了?

换句话说,我不想这样做:

var Cat = function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){
   this.a = a;
   this.b = b;
   //...etc...
};

// inherit functions if any
Cat.prototype = new Animal;

var y = new Cat(1,2,3....);

提前致谢! j

【问题讨论】:

    标签: javascript inheritance constructor


    【解决方案1】:

    记住这样一长串参数的顺序和含义很快就会变得乏味。

    如果您将新动物的属性作为对象传递,您可以增加一些灵活性- 而且它并不像一长串参数索引那么难记。

    function Animal(features){
     for(var p in features){
      this[p]= features[p];
     }
    };
    
    You can give every cat some basic cat features automatically, 
    and add specifics when you make a new cat.
    
    function Cat(features){
     for(var p in features){
      this[p]= features[p];
     }
    }
    Cat.prototype= new Animal({legs: 4, eats: 'meat', type: 'mammal', whiskers: true});
    Cat.prototype.constructor=Cat;
    
    var Tiger= new Cat({tail: true, hunter: true});
    Tiger begins with these properties:
    
    tail: true
    hunter: true
    legs: 4
    eats: meat
    type: mammal
    whiskers: true
    

    【讨论】:

      【解决方案2】:

      怎么样?

      var Cat = Function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){
         Animal.apply(this, arguments);
      };
      
      // inherit functions if any
      Cat.prototype = new Animal;
      
      var y = new Cat(1,2,3....);
      

      【讨论】:

      • "arguments" 是一个非常强大的变量,它会自动在任何函数调用的范围内...查看此处了解更多信息:seifi.org/javascript/javascript-arguments.html
      • Yo 甚至不需要在 Cat 函数中声明参数列表(a、b、c 等)。参数仍将包含在新的 Cat(1,2,3...) 调用中发送的值。
      • 谢谢拉斯!这正是我想要的。
      • 小心:prototype= new Animal 调用实例化了一个Animal,调用构造函数并将所有参数设置为undefined。对于只存储其参数的简单构造函数,这是可以接受的,但对于任何更复杂的东西,它都会中断。背景和(冗长!)讨论:stackoverflow.com/questions/1595611/…
      • 另外,其中的 Animal.apply 位本身不是继承或使用原型。 Animal.apply 可以与任何对象一起调用,也可以是不从 Animal 继承的对象。
      猜你喜欢
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      相关资源
      最近更新 更多