从Javascript中的事件侦听器调用访问对象的属性 [英] Accessing an object's property from an event listener call in Javascript
问题描述
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屋!