从 Javascript 中的事件侦听器调用访问对象的属性 [英] Accessing an object's property from an event listener call in Javascript

查看:38
本文介绍了从 Javascript 中的事件侦听器调用访问对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我正在用 Javascript 创建一个对象.在构造函数中,我正在设置一个事件侦听器.问题是当事件被触发时,找不到 this.prop,并打印出 undefined .我该如何解决这个问题?

Below I am creating an object in Javascript. Within the constructor I am setting up an event listener. The problem is that when the event gets fired, this.prop cannot be found, and undefined prints out. How do I solve this?

   var someObj = function someObj(){
       this.prop = 33;
        this.mouseMoving = function() { console.log(this.prop);}

        document.getElementById("someDiv").addEventListener('mousemove', this.mouseMoving, true);

 }

推荐答案

当事件处理程序被调用时,this"不再引用someObj"对象.您需要将this"捕获到 mouseMoving 函数将捕获的局部变量中.

When the event handler gets called, "this" no longer references the "someObj" object. You need to capture "this" into a local variable that the mouseMoving function will capture.

var someObj = function someObj(){
    this.prop = 33;
    var self = this;
    this.mouseMoving = function() { console.log(self.prop);}

    document.getElementById("someDiv").addEventListener('mousemove', this.mouseMoving, true);
}

我假设someObj 是一个构造函数,即打算用 new someObj() 调用,否则this"将是全局范围.

I'm assuming "someObj is a constructor, i.e. intended to be called with as new someObj(), otherwise "this" will be the global scope.

this"关键字在 JavaScript 中可能会令人困惑,因为它的工作方式与在其他语言中不同.要记住的关键是在调用函数时绑定到调用对象,而不是在创建函数时绑定.

The "this" keyword can be confusing in JavaScript, because it doesn't work the same way as in other languages. The key thing to remember is that it is bound to the calling object when the function is called, not when the function is created.

这篇关于从 Javascript 中的事件侦听器调用访问对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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