從按鈕輸入點擊功能時,有沒有辦法保持類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.obj
在foo()
。
這樣做。這兩種方法有什麼區別?第二個只是調用函數?爲什麼不會'()=> this.foo'然後呢? – shinzou
'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()' –