我正在阅读这段代码
// 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();
rect instanceof Rectangle; // true
rect instanceof Shape; // true
rect.move(1, 1); // Outputs, 'Shape moved.'
这段代码让我很困惑
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
为什么我们不使用 Rectangle.prototype = Shape.prototype,Object.create()
有什么特别之处?
如果 Rectangle.prototype.constructor = Rectangle; 会怎么样?不叫?
最佳答案
如果你执行 Rectangle.prototype = Shape.prototype
那么你对 Rectangle.prototoype
执行的任何修改都会反射(reflect)在 Shape.prototype
因为它们是同一个对象。
为了避免这种情况,我们使用 Object.create(Shape.prototype)
创建了一个新对象,它的原型(prototype)链接指向 Shape.prototype
。
至于Rectangle.prototype.constructor = Rectangle;
,就是要确保new Shape().constructor
指向Rectangle
,不是 Shape
。
函数的原生 prototype
具有指向该函数的 constructor
属性。
例如
function Rectangle() {}
Rectangle.prototype.constructor === Rectangle; //true
现在,当我们执行 Rectangle.prototype = ...
时,我们破坏了该引用,之后需要修复它。
关于javascript - 为什么我们需要在 JavaScript 中定义构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27304726/