使用 Object.create 进行继承

Using Object.create for inheritance?

本文关键字:继承 create Object 使用      更新时间:2023-09-26

这段代码来自 MDN 关于 Object.create() 的文章:

// 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()的StackOverflow问题。,他们没有完全解决我的困惑。

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

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

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

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

  • new Shape()这样做:

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

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