根据mdn文档,当我们在javascript中进行原型继承时,我们正在将构造函数属性重新分配给Child构造函数。
// 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; //If you don't set Object.prototype.constructor to Rectangle,
//it will take prototype.constructor of Shape (parent).
//To avoid that, we set the prototype.constructor to Rectangle (child).
var rect = new Rectangle();
将构造函数重新分配给Rectangle
的实际目的是什么?当使用var rect = new Rectangle()
创建对象时,无论是否重新分配构造函数,我都看不到任何区别。唯一的区别是,如果我注释该代码,则rect.__proto__.constructor
指向Shape
。有人可以解释这样做的真正需要吗?