2017-06-19 118 views
0

你好,這是我的(shortcuted)示例代碼:遺漏的類型錯誤:this.function不是一個函數

export class SolarSystemInfo { 

    constructor() { 
     this.test(); 
    } 

    // click on solar system 
    clickSolarSystem() { 
     $("body").on("click",".hex", function() { 
      this.test(); 
     }); 
    } 

    public test() { 
     alert('test'); 
    } 

} 

我的問題是,在構造函數是測試,稱爲右功能,但在clickSolarSystem打完電話後功能this.test()我得到:遺漏的類型錯誤:this.test不是一個函數
我怎麼也叫測試函數在我的函數內部類?
謝謝

+0

使用測試()不'this'不工作? – Zooly

+0

參見https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this – Ryan

+0

@Zooly:那絕對不行。 – Ryan

回答

3

當執行回調函數時,this的上下文丟失。
要解決,你可以使用arrow function

clickSolarSystem() { 
    $("body").on("click",".hex",() => { 
     this.test(); 
    }); 
} 

或者你可以使用bind method

clickSolarSystem() { 
    $("body").on("click",".hex", function() { 
     this.test(); 
    }).bind(this); 
} 
+0

這可能有助於解釋什麼'this'在每個上下文中引用。 – cdbajorin

+1

@cdbajorin更新了答案 –

+0

感謝您的幫助: –

相關問題