Accessing class member variables inside an event handler in Javascript(在 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"
});
}
这篇关于在 Javascript 中访问事件处理程序中的类成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Javascript 中访问事件处理程序中的类成员变量


基础教程推荐
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01