(function(){ const requestBtn = d.getElementById('reqestInfo'); requestBtn.addEventListener('click', ()=>{ console.log(this) }, false) })() 

and you need to bind this to requestBtn

 (function(){ const requestBtn = d.getElementById('reqestInfo'); requestBtn.addEventListener('click', ()=>{ console.log(this) }.bind(requestBtn), false) })() 

gives a syntax error, but

 (function(){ const requestBtn = d.getElementById('reqestInfo'); requestBtn.addEventListener('click', function(){ console.log(this) }, false) })() 

it turns out right. As far as I understand arrow func also tie this to the context or am I confusing something

  • 3
    not quite sure what the duplicate is, but this question should help: Loss of call context - Grundy
  • I was just looking at this question, and there in principle there is an explanation, but it explains the line between functional JC and object, because for all examples there is an assignment of some kind of f-ii variable. But in the case of anonymous p-mi - question - ddeadlink
  • not, there is absolutely the same thing, it doesn’t matter whether the function was assigned to a variable and called or called immediately upon declaration, the behavior is the same - Grundy
  • hm found, After creating the value of this can not be changed by the above methods. then you have to do an older version .. - ddeadlink
  • I wrote the answer, but more and more it seems to me that it is really a duplicate. - Grundy

1 answer 1

Arrow functions are bound to the current context.

What does it mean?

This means that inside the function the value of this will be the same as at the moment of creation.

Consider the examples from the question:

 (function(){ const requestBtn = d.getElementById('reqestInfo'); requestBtn.addEventListener('click', ()=>{ console.log(this) }, false) })() 

This code is executed inside a self-invoking function. Inside this function, this -> global object, in this case, window . Hence inside the handler, this this persist.

Second example:

 (function(){ const requestBtn = d.getElementById('reqestInfo'); requestBtn.addEventListener('click', ()=>{ console.log(this) }.bind(requestBtn), false) })() 

There is really a syntax error, to fix it you need to wrap the switch function in parentheses

 (()=>{ console.log(this) }).bind(requestBtn) 

But this does not help, since the switch functions cannot change the context obtained during creation.

Now, why does the last example work:

 (function(){ const requestBtn = d.getElementById('reqestInfo'); requestBtn.addEventListener('click', function(){ console.log(this) }, false) })() 

Because, when adding a handler through the addEventListener function, the handler is called in the context of the added element. That is, this is essentially normal behavior, when this inside a handler refers to an element, and all dancings with a change of context are usually due to the fact that you wanted to see this as a handler, not an element, but some third-party object.