简体   繁体   English

为什么dom事件监听器回调中的this值不是窗口?

[英]Why is the value of `this` in a dom event listener callback not the window?

Let's look at the following code: 让我们看下面的代码:

 const div = document.getElementById('foo'); div.addEventListener('click', function() { console.log(this); }); 
 <div id="foo">click me</div> 

This button will always log the dom element I'm clicking. 此按钮将始终记录我单击的dom元素。 I've always known this to be true, and I know that I can use an arrow function here to make the value of this the window . 我一直都知道这是对的,而且我知道我可以在这里使用箭头函数来this window的值设置为window We are assuming non arrow function syntax for this question. 我们假设此问题为非箭头函数语法。

To my knowledge, the value of this gets its value based on how the enclosing function is invoked. 据我所知,值this获取基于封闭函数是如何调用它的价值。 The callback of this event listener certainly doesn't get called on the dom element. 当然,不会在dom元素上调用此事件侦听器的回调。

In my mind, when the div gets clicked, it adds the anonymous function to the message queue. 在我看来,当div被单击时,它会将匿名函数添加到消息队列中。 When the queue is empty it invokes the anonymous function in a global execution context (perhaps this is where I'm wrong). 当队列为空时,它将在全局执行上下文中调用匿名函数(也许这是我错的地方)。

If it is in the global execution context where this anonymous function gets invoked, shouldn't the value of this be the window? 如果是在这个匿名函数被调用的全局执行环境,不应该值this是窗口?

Which leads back to the title question, why is the value of this in a dom event listener callback not the window ? 这就引出了标题问题,为什么在dom事件监听器回调中this值不是window (Assuming the callback is not an arrow function) (假设回调不是箭头函数)

It's because it's a method attached to the div object - think of it like this: 这是因为它是附加到div对象的方法-像这样想:

const div = {
    addEventListener: function(event, callback) {...}
};

In this example, this would refer to div as you would expect. 在此示例中, this将按照您的预期引用div

This is what's actually happening in your code, only it's being defined differently. 这就是代码中实际发生的事情,只是其定义不同。

The value of this within the handler 此值在处理程序中

It is often desirable to reference the element on which the event handler was fired, such as when using a generic handler for a set of similar elements. 通常希望引用触发了事件处理程序的元素,例如在将通用处理程序用于一组相似元素时。

If attaching a handler function to an element using addEventListener() , the value of this inside the handler is a reference to the element. 如果使用addEventListener()将处理程序函数附加到元素,则该函数在处理程序内部的值是对该元素的引用。 It is the same as the value of the currentTarget property of the event argument that is passed to the handler. 它与传递给处理程序的事件参数的currentTarget属性的值相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM