使用 Object.create 进行继承?

Using Object.create for inheritance?

此代码来自 Object.create() 上的 MDN 文章:

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

倒数第三行是我感到困惑的那一行。

有什么区别:

一个。现在怎么样了
B. Rectangle.prototype = Object.create(Shape);
C. Rectangle.prototype = new Shape();

所有 3 个最终不会产生相同的结果吗?在 rect 上定义的相同属性和相同的内存使用来定义它们?

是的,我已经阅读了解决 Object.create() 的其他 Whosebug 问题。 没有,他们没有完全解决我的困惑。

  • Object.create(Shape) return 是一个继承自 Shape 的对象。

    如果你想创建 Shape 的子类,你可能不想这样做。

  • Object.create(Shape.prototype) return 是一个继承自 Shape.prototype 的对象。

    因此,此对象将没有 xy 自己的属性。

  • new Shape() 这样做:

    1. 创建一个继承自 Shape.prototype 的对象。
    2. 调用 Shape,将前一个对象作为 this 传递。
    3. Returns 那个对象(假设 Shape 没有 return 另一个对象)。

    因此,此对象将具有 xy 自己的属性。