2
我一直在閱讀MSD關於Object.create
的文檔,我偶然發現了這個例子。關於Javascript原型清晰度
// 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;
因此,所有我想知道的是什麼?
這樣做有什麼原因(保持對象檢查或其他東西的長期理智)
請閱讀:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor – jfriend00