10

クリックイベントにアタッチされたイベントハンドラーを持つ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)を変更できるようにするにはどうすればよいですか?

4

4 に答える 4

15
function Foo() {
    var _self = this;
    this.num=0;

    $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element.

    this.eventHandler=function() {
        _self.num++;
    }
}

_self = this外側のスコープで定義された参照を使用する

于 2012-05-18T16:12:07.003 に答える
15

関数のコンテキストをバインドする必要があります。それ以外の場合thisは、グローバルオブジェクトになります。

$('element').click($.proxy(this.eventHandler, this));

最新のブラウザでは、次を使用することもできますFunction.prototype.bind

$('element').click(this.eventHandler.bind(this))
于 2012-05-18T16:15:54.723 に答える
2
function Foo() {
   this.num=0;
   $(document).on('click', 'element', this, this.eventHandler);
   this.eventHandler=function(e) {
      var _this = e.data; 
      _this.num++;
   }
}

1)JQuery on()メソッドを使用してイベントリスナーをアタッチします。2)親クラスにアクセスするために参照_thisを使用します。

于 2015-02-16T11:09:42.667 に答える
1

thisイベントハンドラーでアクセスできるコンストラクターにへの参照を格納できます。

function Foo() {

    this.num=0;
    $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element.

    var that = this;
    this.eventHandler=function() {
        that.num++;// This doesn't work.
    }
}
于 2012-05-18T16:12:15.303 に答える