为什么这个代码显示错误

Why this code is showing error?

本文关键字:显示 错误 代码 为什么      更新时间:2023-09-26

第二行显示错误

"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. 你应该使用constructor函数(而不是同名的函数)。
  2. 你不能在类定义中设置成员(你在构造函数中设置),使用this
  3. 您在showOff函数中有一个错字。

更多信息见参考。

修复:

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