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

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

问题描述

下面我在Javascript中创建一个对象。在构造函数中,我正在设置一个事件监听器。问题是当事件被触发时,无法找到this.prop,并且未定义打印出来。我该如何解决?

  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函数捕获的局部变量中。

  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将是全局范围。



this关键字可以在JavaScript中混淆,因为它不像其他语言一样工作。要记住的关键是当函数调用时绑定到调用对象,而不是函数被创建。


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);

 }

解决方案

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);
}

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

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天全站免登陆