我看了一些关于这个主题的答案,但我不确定我理解addEventListener
中this
关键字的工作方式。
const button = document.querySelector('button');
function foo() { console.log(this) }
button.addEventListener('click', foo);
foo
是在 addEventListener
中定义的普通函数,它不是 button
对象的方法。当调用 foo
时,应该在全局对象的上下文中执行,因此 this
应该等于 window
而不是 button
。
看起来类似于这个例子的情况:
const obj = {
method: function (cb) {
console.log('method', this); // `this` === `obj`
return cb();
}
};
obj.method(function() {
console.log('cb', this); // `this` === `window`
});
其中obj
可以被视为button
,method
可以是addEventListener
,而cb
则是addEventListener
内的回调函数。
我知道我可以使用bind
来改变this
的上下文,但我想更深入地了解它为什么能够这样工作。
为什么addEventListener
回调函数中的this
会在当前元素的上下文中调用,而不是全局对象?
foo
是addEventListener
内的一个普通函数,它不是button
对象上的方法。"- 这并不重要。如果你调用foo()
,那么是的,你将不会得到一个this
值(或者在松散模式下是window),但当你使用addEventListener
时,它将在按钮上调用该函数。就像在你的obj
示例中,method
会执行cb.call(obj)
一样。 - Bergibutton.onclick = foo
。在那里,处理程序实际上是一种方法 :-) - Bergi