问题:当子类扩展超类时,为什么示例会将Rectangle.prototype.constructor
设置回Rectangle
?这是最佳做法吗?它是否说明它被重置?因为该示例无论如何都适用。
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(rect);
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.
答案 0 :(得分:2)
当Rectangle.prototype = Object.create(Shape.prototype)时;运行时,它默认将Rectangle的构造函数设置为Shape.prototype.constructor - 这不是你想要的。现在,您必须继续并将Rectangle.prototype.constructor显式设置为Rectangle构造函数,因此任何新对象都将是Rectangle对象。将代码粘贴到此处:http://www.objectplayground.com/,选择“经典继承”,并将“rect”更改为“this.instance = new Rectangle();”。玩弄它,注释掉线条,看看它有什么不同。
希望有意义!