【问题标题】:Using Object.create for inheritance? [duplicate]使用 Object.create 进行继承? [复制]
【发布时间】:2015-03-20 16:41:50
【问题描述】:

这段代码来自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();

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

两者有什么区别:

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

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

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

【问题讨论】:

    标签: javascript inheritance prototype prototypal-inheritance


    【解决方案1】:
    • Object.create(Shape) 返回一个继承自 Shape 的对象。

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

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

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

    • new Shape() 这样做:

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

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

    【讨论】:

    • 您可能应该提到一个不希望原型对象拥有自己的xy 属性...
    • 我只是不明白当您致电Object.create(Shape) 时会发生什么。我知道它不起作用,但我不知道为什么。如果你取出Shape.call(this)这一行并使用Object.create(Shape)而不是Object.create(Shape.prototype),然后实例化一个Rectangle,生成的对象既没有x也没有y也没有move。所以发生了什么事?什么被设置成什么?
    • @Aerovistae 问题在于,由于Shape 是一个函数,Object.create(Shape) 继承自Shape(没有自己的属性)、Function.prototypeObject.prototype。但是,您正在尝试继承 Shape。这意味着您要从Shape.prototype(具有move 方法)和Object.prototype 继承。
    猜你喜欢
    • 2023-03-20
    • 2016-02-15
    • 2023-03-22
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多