javascript - 在 javascript 中调用父类(super class)型方法

标签 javascript

我正在阅读《面向对象 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/

相关文章:

javascript - 添加字母后如何进行替换?

javascript - 在 Symfony/Twig 中转义 tinyMCE javascript 输出

javascript - 为什么我不能将 Javascript Promise 存储在变量中,然后调用 "then"和 "catch"方法?

javascript - React Native 动画 singleValue.stopTracking 不是一个函数

javascript - 使用NPM启动JS项目

javascript - 当用户单击任何列表元素时运行函数

javascript - 基于按钮状态显示/隐藏

javascript - $.ajax 在同一页面提交,表单仅在第一次有效

javascript - 我希望更新未读消息的数量,并在用户收到新消息时播放通知声音。我使用 PHP、MySql、Javascript

javascript - 将 ThreeJS 场景导出到 STL 文件结果导致文件大小非常大