I
I
Iliaity2015-11-14 05:01:14
JavaScript
Iliaity, 2015-11-14 05:01:14

How does the inheritance constructor work?

I came across an example of inheritance through a constructor. And I can't figure out why this line Square.prototype.constructor = Square; According to the author, it is simply necessary.
Please explain why the constructor of the Square prototype is overwritten here?
The code works great without this snippet.

function Rectangle(length, width) {
this.length = length;
this.width = width;
}
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
Rectangle.prototype.toString = function() {
return "[Rectangle " + this.length + "x" + this.width + "]";
};
// inherits from Rectangle
v function Square(size) {
this.length = size;
this.width = size;
}
Square.prototype = new Rectangle();
Square.prototype.constructor = Square;
Square.prototype.toString = function() {
return "[Square " + this.length + "x" + this.width + "]";
};
var rect = new Rectangle(5, 10);
var square = new Square(6);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Inchin ☢, 2015-11-14
@Iliaity

The default prototype always contains a constructor property that points to the constructor function.

function Rabbit(){}
console.log( Rabbit.prototype.constructor ); //Rabbit

The author of the code above overrides prototype in its entirety:
Square.prototype = new Rectangle();
console.log( Square.prototype.constructor ) // Rectangle

Actually, it then assigns the correct value to the constructor (Square).
This is done not for the efficiency of the code, but in order to avoid errors in the future, because when referring to the constructor , we expect to receive a reference to the object's constructor function, and not as its prototype.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question