在 ECMAScript 2021 中,class 已经成为一种常见的面向对象编程的方案,但是在实际使用中,我们可能会遇到各种各样的报错,本文将介绍一些在使用 class 时出现的常见报错,并提供解决方案和示例代码。
报错一:ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
这个错误是由于在派生类的构造函数中没有调用 super() 造成的,例如:
-- -------------------- ---- ------- ----- ------ - ----------------- - --------- - ----- - - ----- --- ------- ------ - ------------- - --------- - ------- - - ----- ----- - --- ------ ------------------- -- ------- ---- ----- ----------- -- ------- ----- ------ --------- ------ -- --------- ---- ------- -----------展开代码
解决方法是在子类构造函数中调用 super()
:
-- -------------------- ---- ------- ----- ------ - ----------------- - --------- - ----- - - ----- --- ------- ------ - ----------------- - ------------ -- ---------- --------- - ------- - - ----- ----- - --- ------------- ------------------- -- ---- ----- -------- ----- ------ -展开代码
报错二:TypeError: Class constructor Animal cannot be invoked without 'new'
这个错误是由于在创建实例时,没有使用 new
关键字造成的,例如:
class Animal { constructor(name) { this.name = name; } } const myDog = Animal('Tommy'); // 报错:TypeError: Class constructor Animal cannot be invoked without 'new'
解决方法是调用时使用 new
关键字:
class Animal { constructor(name) { this.name = name; } } const myDog = new Animal('Tommy'); console.log(myDog); // 输出:{ name: 'Tommy' }
报错三:TypeError: Cannot set property 'xxx' of undefined
这个错误是由于在子类构造函数中访问父类属性时,没有正确调用 super()
造成的,例如:
-- -------------------- ---- ------- ----- ------ - ----------------- - --------- - ----- - - ----- --- ------- ------ - ----------------- - --------- - ------- ------------ ---------- - ------------- ---- -------------- - - ----- ----- - --- ------------- -- ------------- ------ --- -------- ------- -- ---------展开代码
解决方法是先调用 super()
,再访问父类属性:
-- -------------------- ---- ------- ----- ------ - ----------------- - --------- - ----- - - ----- --- ------- ------ - ----------------- - ------------ --------- - ------- ---------- - ------------- ---- -------------- - - ----- ----- - --- ------------- ------------------------- -- -------- ---- ----展开代码
报错四:TypeError: xxx is not a constructor
这个错误是由于在创建实例时,类名没有正确引用造成的,例如:
class Animal { constructor(name) { this.name = name; } } const myDog = new dog('Tommy'); // 报错:TypeError: dog is not a constructor
解决方法是类名大小写要与定义时一致:
class Animal { constructor(name) { this.name = name; } } const myDog = new Animal('Tommy'); console.log(myDog); // 输出:{ name: 'Tommy' }
结论
在使用 class 时,遇到这样的错误并不是什么大问题,只需要仔细查看错误信息并引用示例代码中的解决方法,你就能轻松地解决问题了。同时,还要多多练习,熟悉 ECMAScript 2021 中的 class 用法,才能更好地运用它进行编程。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/670d83095f551281025d6c2f