【发布时间】:2016-05-13 20:39:54
【问题描述】:
我一直在阅读关于Object.create 的MSD 文档,偶然发现了这个例子。
// 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;
那么,我只想知道?
这样做的原因是什么(在对象检查或其他方面保持理智)
【问题讨论】:
标签: javascript prototype