在 Javascript 中访问事件处理程序中的类成员变量

Accessing class member variables inside an event handler in Javascript(在 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 中访问事件处理程序中的类成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
How do I get the HTTP status code with jQuery?(如何使用 jQuery 获取 HTTP 状态码?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)