我正在阅读“面向对象的Javascript原理”一书,我部分地解释了访问超类型方法的问题。我已经在超级原型(重新声明的toString和新函数getArea)上定义了两个函数,并将它们扩展为whit子类,我想在使用它们的返回值时更改超级方法。代码如下所示:
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
问题是,square.getArea()
抛出错误
undefined不是函数
有人可以解释我为什么吗?为什么toString
有效且getArea
没有?
答案 0 :(得分:3)
在这一行
var area = Rectangle.prototype.getArea().call(this);
您试图将getArea()
的结果作为call
的函数调用(这是不可能的,因为getArea
的结果将是数字和数字没有call
方法,只有Function
objects have that)。但是,您应该调用getArea
函数本身,就像这样
var area = Rectangle.prototype.getArea.call(this);