【发布时间】:2016-01-02 21:33:44
【问题描述】:
我无法找到对此的明确解释。这是我在 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();
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.'
【问题讨论】:
-
@TwilightSun:请注意,您可以将问题标记为重复,这将为您生成自动评论,并让用户知道谁有权将问题标记为重复。
标签: javascript prototype