在 Javascript 中访问事件处理程序中的类成员变量
我有一个关于从类使用的事件处理程序内部访问 Javascript 类成员变量的正确方法的快速问题.例如:
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"
});
}
事件处理程序中的this.x"并没有改变Map"类的成员变量,而是试图影响触发事件的元素的x"成员变量.从事件处理程序中访问Map"类的成员变量的正确方法是什么?
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.
干杯,查理
推荐答案
由于 this
在事件上下文中发生变化(通常指向 global
),因此您需要存储一个在活动之外引用自己:
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"
});
}
相关文章