0

Why is the 'this' context of an arrow function the 'window' object and not the element I'm listening for events on?

const chkBox = document.createElement('input');
chkBox.type = 'checkbox';
document.body.appendChild(chkBox);

// Works as expected:
chkBox.addEventListener('change', function () {
    console.log("long fn: ", this.checked, this); // this = checkbox element
});

// 'this' is the window object, so there's no 'checked' property:    
chkBox.addEventListener('change', e => console.log("short fn: ", this.checked, this)); // this = window
nevernew
  • 650
  • 10
  • 23
  • 2
    have a look at https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/#1-this-value – Alberto Sinigaglia Jul 23 '21 at 14:49
  • 1
    The documentation located [Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) describes it well. ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context). Lastly, if the value of this is not set by the call, this will default to the global object, which is window in a browser. – BeerusDev Jul 23 '21 at 14:51
  • Aha, I see, so an arrow function uses whatever the context was where the arrow function was defined - so an arrow function within a class method would use that class's context. Seems useful for not having to call 'apply(this, ...)' or set 'const ctx = this;' every time :) – nevernew Jul 23 '21 at 14:59

0 Answers0