How does rect is an instance of Shape? Shape constructor is not on the prototype chain of rect.
rect.__proto__ : Rectangle.prototype
Rectangle.prototype : Object.prototype
// 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.'
What are the conditions for an object to be an instance of a Constructor?
Shapeprototype is put on the prototype chain ofRectangleby the code you posted.Object.create(Shape.prototype)creates a new object withShape.prototypeas its prototype link. It does not create a copy of theShapeprototype; read the documentation.