我已经尝试通过阅读来理解 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.addEventListener
中 this
将引用 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/