Answer the question
In order to leave comments, you need to log in
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
The default prototype always contains a constructor property that points to the constructor function.
function Rabbit(){}
console.log( Rabbit.prototype.constructor ); //Rabbit
Square.prototype = new Rectangle();
console.log( Square.prototype.constructor ) // Rectangle
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question