为什么此代码显示错误?

Lin*_*ury 1 javascript

第二行显示错误.

"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)"
Run Code Online (Sandbox Code Playgroud)

class CoolGuy {
    specialTrick = null;

    CoolGuy( trick ) {
        specialTrick = trick
    }

    showOff() {
        console.log( "Here's my trick: ", specialTrick );
    }

}

Joe = new CoolGuy("rope climbing");
Joe.shoeOff();
Run Code Online (Sandbox Code Playgroud)

Dek*_*kel 5

  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();
Run Code Online (Sandbox Code Playgroud)