I was going through some links to find out what Object.create functionality has and how does it differs when it comes to create using new as constructor. So I came across this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
This link has a basic example which explains inheritance using Object.create(). Here is the 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();
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.'
Now it explained very nicely how inheritance can be done. But I wanted to know what exactly is the need of this line of code
Rectangle.prototype.constructor = Rectangle;
Does it really required. Eliminating that does not create any issue while running. Am i missing something important here or Does it means optional?
Aucun commentaire:
Enregistrer un commentaire