【问题标题】:What is the advantage of using prototype in combination with new?使用原型和新的结合有什么好处?
【发布时间】:2013-11-08 12:57:02
【问题描述】:

我从一本书中得到了这个继承的例子:

var Animal = function(){};
Animal.prototype.sleep = function(){
    // ...
};

var Cat = function(){};
// Cat is an animal
Cat.prototype = new Animal;
Cat.prototype.meow = function(){
    // ...
};

var scratchy = new Cat();
scratchy.sleep();
scratchy.meow();

但这也有效,对我来说似乎更直观。你为什么不做呢?还是你?它会创建引用而不是复制原型属性吗?

Cat.prototype = Animal.prototype;

【问题讨论】:

  • 我已经尝试创建最完整的 JavaScript 原型,(多重)继承,覆盖,使用 Super 和 this 值答案在这里:stackoverflow.com/a/16063711/1641941 希望它有所帮助,如果您有任何问题,请随时问他们,以便我改进。

标签: javascript inheritance prototype


【解决方案1】:

如果您先添加Cat.prototype = Animal.prototype;,然后尝试添加到Cat.prototype,那么您也添加到了Animal.prototype。当前的最佳实践实际上是

Cat.prototype = Object.create(Animal.prototype);

【讨论】:

    【解决方案2】:
    1. 这意味着对Cat.prototype 的任何更改都将反映到Animal,即出现在超类中的子类方法!
    2. 在构造函数中定义的任何Animal 成员在执行new Cat() 时都将不可用。例如。假设Animal 构造函数是:

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

      前一种方法的Cat 将包含birthDate 属性,第二种方法的Cat 不会。

    【讨论】:

    • 对于您的观点2,执行Cat.prototype = new Animal(); 仍将导致未定义(但已初始化)birthDate,并且所有猫都将被记录为出生于同一日期。如果确实需要调用构造函数,最好使用inheritConstructor.call(this);
    • 是的,你是对的。第二点只有边际有效性。
    【解决方案3】:

    在前面带有Cat.prototype = new Animal 的代码中,您正在调用Animal 构造函数var Animal = function() {};,它将创建一个新对象,运行该构造函数和其中的任何代码,将this 分配给新对象,即原型属性附加到构造函数,并返回新对象。 new 的使用看起来很熟悉如何使用经典继承创建“类”,但 Javascript 使用 PROTOTYPAL Inheritence 来创建从其他对象继承的新对象。

    通过Cat.protoype = Animal.prototype,您并没有在做前面提到的事情,而是将原型分配给彼此,因此如果您向其中一个添加一些东西,它会影响另一个。

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多