I'm learning prototype based OOP in javascript recently. After reading lots of websites explaining the prototype mechanism in javascript, I settle down with this approach from Mozilla
Here are some snippets from Mozilla:
// 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 understand that Rectangle.prototype = Object.create(Shape.prototype);
will set the prototype chain properly so that instance of Rectangle
will inherit methods from Shape
.
But the Rectangle.prototype.constructor = Rectangle;
line is a little bit confusing.
From this website I know that when we create a new object like function MyClass(){}
, javascript will set its prototype to an empty object and the MyClass.prototype.constructor
will point back to MyClass
. So Rectangle.prototype.constructor = Rectangle;
will fix the broken link since Object.create(Shape.prototype).constructor
still points to Shape
.
But if I remove this line, I will still get the following code running without a problem. I'm just feeling curious if there's any use case for the constructor attribute? What will go wrong if I just leave it pointing to the super class?