将原型与新原型结合使用有什么优势

What is the advantage of using prototype in combination with new?

本文关键字:原型 什么 新原型 结合      更新时间:2023-09-26

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

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;

如果您执行Cat.prototype = Animal.prototype;然后尝试添加到Cat.prototype,则也会添加到Animal.prototype。当前的最佳实践实际上是

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

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

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

Cat.prototype = new Animal前面的代码中,您将调用 Animal 构造函数var Animal = function() {};该函数,该函数将创建一个新对象,

运行该构造函数及其中的任何代码,将this分配给新对象,prototype 属性附加到构造函数,并返回新对象。new的使用看起来很熟悉如何创建具有经典继承的"类",但Javascript使用PROTOTYPAL Inheritence来创建从其他对象继承的新对象。

通过执行Cat.protoype = Animal.prototype您没有做前面提到的操作,您将原型相互分配,因此,如果您向一个添加某些内容,它将影响另一个。