考虑以下代码
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/