57

我一直在尝试围绕Object.createECMAScript 5 中引入的新方法。

通常当我想使用继承时,我会这样做:

var Animal = function(name) { this.name = name; }
Animal.prototype.print = function() { console.log(this.name); }

var Dog = function() 
{ 
  return Animal.call(this, 'Dog'); 
}

Dog.prototype = new Animal();
Dog.prototype.bark = function() { console.log('bark'); }

我只是将一个新创建的 Animal 对象分配给 Dog 的原型,一切都像一个魅力:

var dog1 = new Dog();
dog1.print(); // prints 'Dog'
dog1.bark(); // prints 'bark'
dog1.name; //prints 'Dog'

但是人们(没有解释)说这Dog.prototype = new Animal();不是继承的工作方式,我应该使用 Object.create 方法:

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

这也有效。

使用有什么好处Object.create或者我错过了什么?

更新:有人说这Dog.prototype = Animal.prototype;也可以。所以现在我完全糊涂了

4

4 回答 4

125

在下文中,我假设您只对为什么Object.create设置继承更可取感兴趣。

为了理解它的好处,让我们首先澄清一下 JavaScript 中的“类”是由什么组成的。你有两个部分:

  1. 构造函数。该函数包含创建“类”实例的所有逻辑,即实例特定代码。

  2. 原型对象。这是实例继承的对象。它包含应该在所有实例之间共享的所有方法(和其他属性)。

继承建立了一个is-a关系,例如, a Dog is an Animal。这如何用构造函数和原型对象表示?

显然,狗必须具有与动物相同的方法,即Dog 原型对象必须以某种方式合并Animal 原型对象中的方法。有多种方法可以做到这一点。你会经常看到这样的:

Dog.prototype = new Animal();

这是因为Animal 实例继承自Animal 原型对象。但这也意味着每只狗都继承自一个特定的Animal 实例。这似乎有点奇怪。实例特定代码不应该只在构造函数中运行吗?突然之间,特定于实例的代码和原型方法似乎混合在一起了。

此时我们实际上并不想运行特定于Animal 实例的代码,我们只想要Animal 原型对象中的所有方法。这就是Object.create让我们做的事情:

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

这里我们不是创建一个新Animal实例,我们只是获取原型方法。特定于实例的代码在构造函数内准确地执行:

function Dog() { 
   Animal.call(this, 'Dog'); 
}

最大的优点是Object.create永远有效new Animal()仅当构造函数不期望任何参数时才使用。想象一下,如果构造函数看起来像这样:

function Animal(name) { 
    this.name = name.toLowerCase();
}

你总是必须将一个字符串传递给Animal,否则你会得到一个错误。当你做的时候你会通过什么Dog.prototype = new Animal(??);?你传递哪个字符串实际上并不重要,只要传递something,这有希望向你表明这是一个糟糕的设计。


有人说也Dog.prototype = Animal.prototype;可以。所以现在我完全糊涂了

Animal.prototype从to中“添加”属性的所有内容都Dog.prototype将“起作用”。但是解决方案的质量不同。在这种情况下,您将遇到您添加的任何方法Dog.prototype也将添加到Animal.prototype.

例子:

Dog.prototype.bark = function() {
    alert('bark');
};

因为Dog.prototype === Animal.prototype,所有Animal实例bark现在都有一个方法,这肯定不是你想要的。

Object.create(甚至new Animal)通过创建一个继承自的新对象Animal.prototype并将新对象变为Dog.prototype.


ES6 中的继承

ES6 引入了一种新语法来创建构造函数和原型方法,如下所示:

class Dog extends Animal {

  bark() {
    alert('bark');
  }

}

这比我上面解释的更方便,但事实证明,它extends也使用内部等效项Object.create来设置继承。请参阅ES6 草案中的步骤 2 和 3 。
这意味着 usingObject.create(SuperClass.prototype)是 ES5 中“更正确”的方法。

于 2013-06-30T17:48:42.953 回答
9

首先,运行Animal构造函数可能会产生不希望的副作用。考虑一下:

var Animal = function(name) {
    this.name = name;
    Animal.instances.push(this);
};
Animal.instances = [];

此版本将跟踪已创建的所有实例。你不希望你Dog.prototype被记录在那里。

其次,Dog.prototype = Animal.prototype这是一个坏主意,因为那将意味着这bark将成为Animal.

于 2013-06-30T17:42:50.687 回答
8

我想稍微说明一下区别:

这是您编写时基本上发生的事情new Animal()

    //creating a new object
    var res = {};

    //setting the internal [[prototype]] property to the prototype of Animal
    if (typeof Animal.prototype === "object" && Animal.prototype !== null) {
        res.__proto__ = Animal.prototype;
    }

    //calling Animal with the new created object as this
    var ret = Animal.apply(res, arguments);

    //returning the result of the Animal call if it is an object
    if (typeof ret === "object" && ret !== null) {
        return ret;
    }

    //otherise return the new created object
    return res;

这是基本上发生的事情Object.create

    //creating a new object
    var res = {};

    //setting the internal [[prototype]] property to the prototype of Animal
    if (typeof Animal.prototype !== "object") {
        throw "....";
    }
    res.__proto__ = Animal.prototype;

    //return the new created object
    return res;

所以它做同样的事情,但它不调用Animal函数,它也总是返回新创建的对象。在您的情况下,您最终会得到两个不同的对象。使用第一种方法,您将获得:

Dog.prototype = {
    name: undefined,
    __proto__: Animal.prototype
};

用第二种方法你得到:

Dog.prototype = {
    __proto__: Animal.prototype
};

您实际上并不需要name在原型中拥有该属性,因为您已经Dog使用Animal.call(this, 'Dog');.

您的主要目标是让您的Dog实例访问Animal原型的所有属性,这两种方法都可以实现。然而,第一种方法会做一些额外的事情,这些事情在您的情况下并不真正需要,甚至会导致像 Pumbaa80 提到的那样不想要的结果。

于 2013-06-30T18:13:31.757 回答
7

让我们只用代码来理解它;

A.prototype = B.prototype;

function B() {console.log("I am B");this.b1= 30;}
    B.prototype.b2 = 40;

    function A() {console.log("I am A");this.a1= 10;}
    A.prototype.a2 = 20;

    A.prototype = B.prototype;

    A.prototype.constructor = A; 

    var a = new A;
    var b = new B;

    console.log(a);//A {a1: 10, b2: 40}
    console.log(b);//B {b1: 30, b2: 40}

    console.log(A.prototype.constructor);//A
    console.log(B.prototype.constructor);//A
    console.log(A.prototype);//A {b2: 40}
    console.log(B.prototype);//A {b2: 40}
    console.log(a.constructor === A); //true
    console.log(b.constructor === A); //true

console.log(a.a2);//undefined

在此处输入图像描述

A.prototype = Object.create(B.prototype);

function B() {console.log("I am B");this.b1= 30;}
B.prototype.b2 = 40;

function A() {console.log("I am A");this.a1= 10;}
A.prototype.a2 = 20;

A.prototype = Object.create(B.prototype);

A.prototype.constructor = A; 

var a = new A;
var b = new B;

console.log(a);//A {a1: 10, constructor: function, b2: 40}
console.log(b);//B {b1: 30, b2: 40} 

console.log(A.prototype.constructor);//A
console.log(B.prototype.constructor);//B
console.log(A.prototype);//A {constructor: function, b2: 40}
console.log(B.prototype);//B {b2: 40}
console.log(a.constructor === A); //true
console.log(b.constructor === B); //true
console.log(a.a2);//undefined

在此处输入图像描述

于 2014-01-30T16:10:34.557 回答