1

I have a test function:

function test(element) {
    console.log(element.id);
    console.log(element);
}

which I want to use as a callback when my button <button id="testbtn">afsdasd</button> is pressed. If I do this:

document.getElementById('testbtn').onclick = () => { 
    test(this); 
};

I get the following output: enter image description here However, if I do this:

document.getElementById('testbtn').onclick = function() { 
    test(this); 
};

the output is different: enter image description here Why? I thought both versions were exactly the same?

Jan Berndt
  • 913
  • 1
  • 10
  • 22

1 Answers1

0

The first one is an arrow function while the second one is a regular function. Arrow functions do not have their own this binding, so they will search this in the next outer lexical scope. In your case the enclosing lexical scope for the arrow function is the Window object.

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Addis
  • 2,480
  • 2
  • 13
  • 21