回顾这个伟大的tutorial: Understanding Classes in JavaScript作者:Tania Rascia,我在查看如何操作时遇到了此错误 extend a class .
class Hero {
constructor(name, level) {
this.name = name
this.level = level
}
// Adding a method to the constructor
greet() {
return `${this.name} says hello.`
}
}
// Creating a new constructor from the parent
function Mage(name, level, spell) {
// Chain constructor with call
Hero.call(this, name, level)
this.spell = spell
}
VM3527:4 Uncaught TypeError: Class constructor Hero cannot be invoked without 'new' at new Mage (:4:8) at :1:15
当使用不带 class
关键字的函数时,此将按预期工作。
function Hero(name, level) {
this.name = name;
this.level = level;
}
最佳答案
由于错误消息是对其自身的描述,因此如果不尝试创建它的新实例,就无法调用构造函数。
var myHeor = new Hero(name, level);
无需创建实例即可调用的唯一方法是 static方法
关于javascript - 未捕获的类型错误 : Class constructor Hero cannot be invoked without 'new' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57432914/