简体   繁体   English

为什么此代码显示错误?

[英]Why this code is showing error?

The 2nd line is showing error. 第二行显示错误。

"ReferenceError: specialTrick is not defined
    at CoolGuy.showoff (<anonymous>:23:40)
    at <anonymous>:31:5
    at Object.InjectedScript._evaluateOn (<anonymous>:875:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)
    at Object.InjectedScript.evaluate (<anonymous>:664:21)"

 class CoolGuy { specialTrick = null; CoolGuy( trick ) { specialTrick = trick } showOff() { console.log( "Here's my trick: ", specialTrick ); } } Joe = new CoolGuy("rope climbing"); Joe.shoeOff(); 

  1. You should use the constructor function (and not a function with the same name). 您应该使用constructor函数(而不是同名的函数)。
  2. You can't set members inside the class definition (you set them inside the constructor), using this . 您不能使用this在类定义内设置成员(在构造函数内设置成员)。
  3. You had a typo in the showOff function. 您在showOff函数中遇到了错字。

More information in the reference . 参考中有更多信息。

Here is the fix: 解决方法是:

 class CoolGuy { constructor( trick ) { this.specialTrick = trick } showOff() { console.log( "Here's my trick: ", this.specialTrick ); } } Joe = new CoolGuy("rope climbing"); Joe.showOff(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM