This code is from the MDN article on Object.create()
:
// 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();
The third to last line is the one that I'm confused about.
What would be the difference between:
A. how it is now.
B. Rectangle.prototype = Object.create(Shape);
C. Rectangle.prototype = new Shape();
Wouldn't all 3 ultimately yield the same result? The same attributes defined on rect
and the same use of memory to define them?
Yes, I have read the other StackOverflow questions addressing Object.create()
. No, they did not fully address my confusion.