在Javascript中访问事件处理程序中的类成员变量 [英] Accessing class member variables inside an event handler in Javascript

查看:93
本文介绍了在Javascript中访问事件处理程序中的类成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于从类内使用的事件处理程序内部访问Javascript类成员变量的正确方法的快速问题。例如:

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

$(body)。mousemove(function(event){
this.x = event.pageX; //无法访问Map的成员变量x
this.y = event.pageY; //无法访问Map的成员变量y
});
}

而不是更改Map类的成员变量,this事件处理程序中的.x会尝试影响触发事件的元素的x成员变量。什么是访问事件处理程序中Map类的成员变量的正确方法?



任何帮助将不胜感激 - 我一直在



Cheers,
Charlie

解决方案

由于此事件上下文中的更改(通常指向 global ),您需要存储引用在事件之外的自己:

  function Map(){
this.x = 0;
this.y = 0;
var _self = this;
$(body)。mousemove(function(event){
_self.x = event.pageX; //现在可以访问Map的成员变量x
_self.y = event.pageY; //现在可以访问Map的成员变量y
});
}


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:

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

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

Rather than changing the member variable of the "Map" class, the "this.x" in the event handler tries to affect the "x" member variable of the element that triggered the event. What is the proper way to access the member variables of the "Map" class from within the event handlers?

Any help would be greatly appreciated - I've been sort of scratching my head at this one.

Cheers, Charlie

解决方案

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

这篇关于在Javascript中访问事件处理程序中的类成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆