Accessing class member variables inside an event handler in Javascript

后端 未结 3 681
执笔经年
执笔经年 2020-12-24 07:10

I have a quick question regarding the proper way to access Javascript class member variables from inside of an event handler that class uses. For example:

fu         


        
3条回答
  •  醉话见心
    2020-12-24 08:13

    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"
        });
    }
    

提交回复
热议问题