【问题标题】:Mimicking classical inheritance with Object.create()用 Object.create() 模仿经典继承
【发布时间】:2018-04-16 05:10:50
【问题描述】:

我正在浏览 MDN 上的一个主题。我大约完成了一半,我无法完全掌握正在发生的事情。我希望能够阅读此代码,但我被卡住了。任何帮助或意见将不胜感激。

Classical inheritance with Object.create()

  • 第一个函数Shape() 很简单。它是一个构造函数。
  • 下一部分也很简单。 Shape.prototype.move 是添加到 Shape 原型的方法。
  • 下一个构造函数Rectangle() 是我开始失去它的地方。我将Shape.call(this) 翻译成Shape 调用一个对象this。但是this 指向什么?为什么需要这条线?
  • 在倒数第二节中,我可能完全迷失了方向。 Rectangle.prototype = Object.create(Shape.prototype) 这是否意味着将 Rectangle 原型设为 Shape 原型?
  • 最后一项我无法翻译。 Rectangle.prototype.constructor = Rectangle。实际发生了什么?

// 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();

console.log('Is rect an instance of Rectangle?',
  rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?',
  rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

【问题讨论】:

标签: javascript object inheritance


【解决方案1】:

this 是在 Rectangle 构造函数中新创建的 Rectangle 实例。

  Shape.call(this);

将调用 Shape 构造函数,this 是新的 Rectangle。需要这一行,以便这...

  this.x = 0;
  this.y = 0;

... 在 Rectangle 上执行。


  Rectangle.prototype = Object.create(Shape.prototype)

这里定义了 Rectangles 原型继承自 Shapes 原型,所有 Rectangles 都从该原型继承。因此,所有的 Rectangles 也会获得 Shapes 方法。


  Rectangle.prototype.constructor = Rectangle

这只是确保.constructor() 像在矩形上执行的那样工作:

  const rect = new Rectangle();
  const rect2 = new rect.constructor();

【讨论】:

  • 100% 迷人!这条线是否意味着它选择了 Shapes 方法并丢失了自己的方法,或者这是 += 的情况? Rectangle.prototype = Object.create(Shape.prototype)
  • @DR01D 属性在对象本身中查找(例如rect),然后在其原型中(Rectangle.prototype),然后在原型原型中(Shape.prototype),然后在原型中原型原型 (Object.prototype) 所以是的,它不会丢失它的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 2012-10-13
  • 1970-01-01
  • 2023-03-20
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多