javascript - 扩展原型(prototype)、继承和 super

标签 javascript class inheritance ecmascript-6

考虑以下代码

const A = class {
    constructor(...args) {
        A.prototype.constructor.apply(this, args);
    }
};

A.prototype.constructor = function(name) {
    this.name = name;
};

A.prototype.print = function() {
    console.log(this.name);
};


const B = class extends A {};

B.prototype.print = function() {
    super.print();
    console.log('In B!');
};

super.print()行在B.prototype.print抛出语法错误 'super' keyword unexpected here 。为什么?

为什么我不能像其他语言一样调用类的 super ?这样做的正确方法是什么?

最佳答案

在 JavaScript 中,要调用基类的实现,您可以通过名称显式调用它,即:

B.prototype.print = function() {
    A.prototype.print.call(this);
    console.log('In B!');
};

关于javascript - 扩展原型(prototype)、继承和 super ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43183897/

相关文章:

c# - 我有一个基类。如何为正确的派生类调用正确的方法?

javascript - 使用 Angular 和 Parse.com 获取

java - 尝试加载 JRuby 脚本时出错

php - 尝试在方法外使用 dirname() 初始化此公共(public)类变量时出错

php - Doctrine Inheritance - 从 Joined table 继承 Single_Table

Java:在父类(super class)构造函数中从子类调用的方法

javascript - 如何在没有 onclick 事件的情况下使用 javascript 更改图像?

javascript - 求购自动生成问候语 onload

c++ - (继承类)c++ 不存在默认构造函数