2016-11-04 97 views
1

第二行顯示錯誤。爲什麼這段代碼顯示錯誤?

"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

也許你應該定義specialTrick – user2182349

+0

也許嘗試'VAR specialTrick'(或'讓specialTrick'在ES6) –

+0

https://webkit.org/blog/1544/web-inspector-understanding-stack-traces/ – Isaac

回答

5
  1. 您應該使用constructor功能(而不是具有相同名稱的功能)。
  2. 使用this,您不能在類定義內設置成員(您在構造函數中設置它們)。
  3. 您在showOff函數中有錯字。

更多信息in the reference

這裏是修復:

class CoolGuy { 
 

 
    constructor(trick) { 
 
     this.specialTrick = trick 
 
    } 
 

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

 
Joe = new CoolGuy("rope climbing"); 
 
Joe.showOff();