Accessing class member variables inside an event handler in Javascript

点点圈 提交于 2019-11-29 23:06:09

Since this changes in an event context (points to global usually), you need to store a reference to yourself outside of the event:

function Map() {
    this.x = 0;
    this.y = 0;
    var _self = this;
    $("body").mousemove( function(event) {
        _self.x = event.pageX;     // Is now able to access Map's member variable "x"
        _self.y = event.pageY;     // Is now able to access Map's member variable "y"
    });
}

The solution that Matt gave it probably the way to go.

Just thought I'd point out that you can pass data via the event object like this:

function Map() {
    this.x = 0;
    this.y = 0;

// Pass object with data-------------v
    $("body").bind('mousemove', {ths: this}, function(event) {
            // access this via event.data
        event.data.ths.x = event.pageX;
        event.data.ths.y = event.pageY;     
    });
}

This is just for the info. It is really not a practical application. Matt's reference to a local variable makes more sense.

You can also use JQuery.proxy, to create a proxy function with its context. You can than bind the proxy to events.

Here is an example:

var init_handler  =  $.proxy(this.init, this);
$('#page_id').bind('pageinit', init_handler);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!