I have a question about a code demonstrating inheritance in javascript. The code is based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
You can see live demo here: https://jsfiddle.net/gk6xar8w/3/
Here's the code:
// Shape - superclass
function Shape() {
this.x = 1;
this.y = 2;
}
// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.',this.x,this.y);
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
console.log("###### Inside Rectangle.constructor ######");
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
//If you don't set Rectangle.prototype.constructor to Rectangle,
//it will take the prototype.constructor of Shape (parent).
//To avoid that, we set the prototype.constructor to Rectangle (child).
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, 2); // Outputs, 'Shape moved. 2, 4'
rect.move(1, 2); // Outputs, 'Shape moved. 3, 6'
I have two questions.
Firstly, I'm not sure what the effect of Rectangle.prototype.constructor = Rectangle is. Even when I comment this line out, I still get same output. To help me understand I am logging "#### Inside Rectangle.constructor #####" inside function Rectangle() {...}. But this logs even when I comment out Rectangle.prototype.constructor = Rectangle.
Secondly, last two lines which both are rect.move(1, 2), they don't behave as I expected. First invocation outputs 2, 4 and the second outputs 3, 6.
We start with this.x = 1 and this.y = 2 defined inside parent class. First time we invoke rect.move(1,2) it adds for x: 1+1=2 and y: 2+2=4 as expected. But second time around, it doesn't x: 2+2=4 and y: 4+4=8 as expected. Instead it keeps the initial values of this.x = 1 and this.y = 2 and does x: 1+2=3 and y: 2+4=6.
It would be great if I can fix the code so that first invocation of rect.move(1,2) outputs 2, 4 and second invocation ouputs 4, 8 and third outputs 8, 16 and so on.
Thanks.
(1, 2). I'm not sure why you expect the results to be differentxandyare persisting. Break it down; start withx: 1, y: 2, then add(1, 2)so that'sx: 1 + 1 = 2andy: 2 + 2 = 4. The values are nowx: 2, y: 4. Then add(1, 2)again so it'sx: 2 + 1 = 3andy: 4 + 2 = 6