I am reading this piece of code
// 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.'
I got really confused by this snippet
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Why don't we use Rectangle.prototype = Shape.prototype, anything special that Object.create() does?
and what if Rectangle.prototype.constructor = Rectangle; is not called?
Why don't we use Rectangle.prototype = Shape.prototypeA Rectangle is a Shape but not every Shape is a Rectangle. Changing Rectangle.prototype would change Shape.prototype. Constructor is repaired for consistency in case someone wants to use it (and console logging in Chrome). More on constructor, prototype, inheritance, mix ins and so on here: stackoverflow.com/a/16063711/1641941