【发布时间】: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.'
【问题讨论】:
-
@melpomene 我对通用调用没有任何问题。但在这种情况下,我迷路了。函数调用对象。但这对我来说看起来不标准。我跟不上。
标签: javascript object inheritance