Reputation: 5635
I'm reading book The Principles of Object-Oriented Javascript and I'm stuck at part, where accessing supertype methods is explained. I have defined two functions on super prototype(redeclared toString and new function getArea) and extended them whit child class, in which i want to change super methods while using their return value. Code look like this:
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
function Square(size) {
Rectangle.call(this, size, size);
}
Square.prototype = Object.create(Rectangle.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: Square,
writable: true
}
});
// call the supertype method
Square.prototype.toString = function () {
var text = Rectangle.prototype.toString.call(this);
return text.replace("Rectangle", "Square");
};
Square.prototype.getArea = function () {
var area = Rectangle.prototype.getArea().call(this);
return area * 2;
};
var rectangle = new Rectangle(2, 2);
console.log(rectangle); //instance of Rectangle
console.log(rectangle.toString()); // [Rectangle 2x2]
console.log(rectangle.getArea()); //4
var square = new Square(2);
console.log(square); //instance of Square
console.log(square.toString()); // [Square 2x2]
console.log(square.getArea()); //expected 8, got ERROR
Problem is, square.getArea()
throws the error
undefined is not a function
Can someone explain me why? Why toString
works and getArea
not?
Upvotes: 2
Views: 959
Reputation: 239453
In this line
var area = Rectangle.prototype.getArea().call(this);
you are trying to invoke the result of getArea()
as a function with call
(which is not possible, as the result of getArea
will be a number and numbers don't have call
method, only Function
objects have that). But, you should be invoking the getArea
function itself, like this
var area = Rectangle.prototype.getArea.call(this);
Upvotes: 3