使用 Object.create() 模拟经典继承



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

使用 Object.create(( 的经典继承

  • 第一个功能Shape()非常简单。 它是一个构造函数。
  • 下一节也很简单。 Shape.prototype.move是添加到形状原型的方法。
  • 下一个构造函数Rectangle()是我开始失去它的地方。 我Shape.call(this)翻译为Shape调用一个this的对象。 但是this指向什么,为什么需要这条线?
  • 在倒数第二节中,我可能会彻底迷失。 Rectangle.prototype = Object.create(Shape.prototype) 这是否意味着使矩形原型成为形状原型?
  • 最后一项我无法翻译。 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.'

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

  Shape.call(this);

将调用 Shape 构造函数,其中 this 是新的矩形。需要此行,以便...

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

。在矩形上执行。


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

这里定义了矩形原型(所有矩形都从中扩展(继承自形状原型。因此,所有矩形也都获取形状方法。


  Rectangle.prototype.constructor = Rectangle

这只能确保.constructor()像在矩形上一样工作:

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

最新更新