javascript - 当方法绑定(bind)到事件监听器时, "this"未定义

标签 javascript this addeventlistener event-listener

我已经尝试通过阅读来理解 this 关键字的含义。好吧,那没有帮助。所以请帮我解决这个问题!
手动函数调用和绑定(bind)事件监听器的区别在哪里?

var app = {
    foo: true,
    bar: function() {
        console.log("this",this.foo);
        console.log("app",app.foo);
    }
}

app.bar();
/*  this true
    app true    */

document.addEventListener("click", app.bar);
/*  this undefined
    app true    */

感谢您的帮助

最佳答案

在您的 document.addEventListenerthis 将引用 document,因为您正在调用 document 的函数目的。当您直接调用 app.bar() 时,出于同样的原因,this 引用 app 对象。
如果您想引用 app,您必须使用 bind() 手动重新定义函数的上下文:

document.addEventListener("click", app.bar.bind(app));

关于javascript - 当方法绑定(bind)到事件监听器时, "this"未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16857216/

相关文章:

使用 Plates 进行 Javascript (nodejs) 模板化

c# - 如何在对象快速初始化中传递 'this' 引用

Javascript:类属性在拖动事件期间变得未定义

javascript - 获取元素的事件监听器

javascript - 法语字符 html - javascript

javascript - 我们可以在 Javascript/jQuery 中添加 if/else 语句吗 "innerhtml"

javascript - 等待 localhost 在 ASP.NET Core 中重新加载

javascript - 在 Meteor 中使用 Jquery $(this)

java - 如果存在,Java 中的 this() 应该始终首先执行吗?

javascript - HTML5/JS 存储事件处理器