我正在浏览一些链接,以了解Object.create功能有哪些,以及在使用new作为构造函数创建时它有何不同。所以我遇到了这个链接:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
此链接有一个基本示例,它解释了使用Object.create()的继承。这是代码
// 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.'
现在它非常清楚地解释了如何进行继承。但我想知道这行代码究竟是什么需要
Rectangle.prototype.constructor = Rectangle;
真的需要吗?消除它不会在运行时产生任何问题。我错过了这里重要的事情还是意味着可选?