クリックイベントにアタッチされたイベントハンドラーを持つFooというクラス(または関数を含むオブジェクト。Javascriptクラスのようなものはないと聞いています)があります。イベントハンドラーが呼び出されたら、クラスFooのプロパティを変更したいと思います。通常はthis
キーワードを使用しますが、イベントハンドラーでは、this
参照はhtml要素への参照に設定されます。これが私のコードです:
function Foo() {
this.num=0;
$('element').click(this.eventHandler);// jQuery to attach an onclick event to my element.
this.eventHandler=function() {
this.num++;// This doesn't work.
// Normally, "this" would refer to my instance of Foo,
// but as an event handler, "this" refers to the html element.
}
}
だから私の質問は:Fooのインスタンスへの参照をイベントハンドラーに取得して、そのプロパティ(のようなnum
)を変更できるようにするにはどうすればよいですか?