问题描述
我有一个关于从类使用的事件处理程序内部访问 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"
});
}
这篇关于在 Javascript 中访问事件处理程序中的类成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)