[英]Keeping class this when calling button click function
通過按鈕輸入單擊功能時,是否可以將this
保留為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
}
但是我想在foo()
訪問this.obj
。
您需要綁定foo
$("#someButton").click(this.foo.bind(this));
或使用箭頭功能
$("#someButton").click(() => this.foo());
為什么不為函數foo定義參數:
$("#someButton").click(function(){ foo(obj); }); foo(obj){ // work with obj ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.