我正在阅读《面向对象 Javascript 原理》一书,我被困在解释访问父类(super class)型方法的部分。我在 super 原型(prototype)上定义了两个函数(重新声明为 String 和新函数 getArea),并将它们扩展为子类,其中我想在使用它们的返回值时更改 super 方法。代码如下所示:
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 is not a function
有人可以解释一下为什么吗?为什么toString
有效而getArea
无效?
最佳答案
在这一行
var area = Rectangle.prototype.getArea().call(this);
您正在尝试将 getArea()
的结果调用为 call
的函数(这是不可能的,因为getArea
将是一个数字,数字没有 call
方法,只有 Function
objects have that )。但是,您应该调用 getArea
函数本身,如下所示
var area = Rectangle.prototype.getArea.call(this);
关于javascript - 在 javascript 中调用父类(super class)型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29775793/