为什么 Object.create() 在这种情况下用于原型继承?

Why is Object.create() used in this case in prototypical inheritance?

考虑这段代码:-

function Rectangle(length, width) { 
    this.length = length;
    this.width = width;
}

Rectangle.prototype.getArea = function() {
    return this.length * this.width;
};

function Square(size) { 
    Rectangle.call(this, size, size);
}

Square.prototype = Object.create(Rectangle.prototype);

var rect = new Rectangle(5, 5);
var square = new Square(7);

console.log(rect.getArea());   // 25
console.log(square.getArea()); // 49

为什么我们要这样继承:-

Square.prototype = Object.create(Rectangle.prototype);

而不是这样:-

Square.prototype = Rectangle.prototype;

他们似乎都完成了要求的任务。

设置Square.prototype = Rectangle.prototype意味着它们都是同一个对象,这几乎肯定不是您想要的。 Square 是 Rectangle,但 Rectangle 不是 Square,因此行为不会相同。您需要两个不同的原型对象。

使用 Object.create() 是创建对象的一种干净方式,该对象将给定对象(在本例中为 Rectangle.protoype)作为其原型链的头部。结果是 Square.prototype 是一个独特的对象,可以赋予它自己的属性(适用于正方形但不适用于矩形的特殊方法),但它也可以访问 Rectangle 原型中的方法。

因此,当您通过 new Square(100) 创建一个 Square 时,您会得到一个对象,其直接原型是使用 Object.create() 创建的对象,并且(大概)装饰有各种有趣的 Square 行为。 That 对象又将 Rectangle.prototype 作为其原型链中的第一件事。其效果是,如果您调用 mysquare.area(),并且 area() 定义在 Rectangle 原型上,查找将从 Square 实例继续进行,到 Square 原型,然后到 Rectangle将在其中找到该方法的原型。

Object.create 在目标原型之上添加另一个对象。这意味着您可以在不修改原始原型的情况下在此对象上设置属性