从 JavaScript 中的事件侦听器调用访问对象的属性

新手上路,请多包涵

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

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

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

原文由 Ronald 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 275
2 个回答

当调用事件处理程序时,“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 是一个构造函数,即打算用 as new someObj() 调用,否则“this”将是全局范围。

“this”关键字在 JavaScript 中可能会造成混淆,因为它的工作方式与在其他语言中不同。要记住的关键是它 在调用函数时 绑定到调用对象,而不是在创建函数时。

原文由 Matthew Crumley 发布,翻译遵循 CC BY-SA 2.5 许可协议

javascript 内置的 Function.prototype.bind() 就是为了这个目的。

例如:

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

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

 }

更多关于绑定方法的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

否则你必须将对象 someObj 的引用传递给元素并在行中使用该引用:

 console.log(this.referenceToObject.prop); //this references the DOM element in an event.

原文由 Itay Moav -Malimovka 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题