2017-05-29 53 views
0

從按鈕輸入點擊功能時,有沒有辦法保持類this在調用按鈕點擊功能時保持此類

例如:

class MyClass extends FooClass{ 

    constructor (obj) { 

    super (obj) 

    this.obj= obj; 

    $("#someButton").click(this.foo); 
    } 

    foo(){ 
    this.obj; // undefined because this is now #someButton and not MyClass 
    } 

但我想訪問this.objfoo()

回答

5

您需要綁定foo

$("#someButton").click(this.foo.bind(this)); 

,或者使用箭頭功能

$("#someButton").click(() => this.foo()); 
+0

這樣做。這兩種方法有什麼區別?第二個只是調用函數?爲什麼不會'()=> this.foo'然後呢? – shinzou

+1

'bind'通過有界的上下文創建新的函數,這是ES5在回調中保持上下文的方式。 '()=> blah'創建新的箭頭函數,並在ES201Somthing中引入。他們在某些方面有所不同,但在這種情況下應該工作「相同」https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions 「爲什麼不會'()=> this.foo'工作呢?「 '()=> body'創建新的箭頭函數'this.foo',簡單地訪問'foo' w/o調用。所以你需要'this.foo()' –

-1

你爲什麼不定義函數foo的參數:

$("#someButton").click(function(){ 
 
    foo(obj); 
 
}); 
 

 

 
foo(obj){ 
 
    // work with obj ... 
 
}

+1

他將如何訪問'foo'? –