addEventListener, arrow functions, and `this` [duplicate]

What is this?

this is a special keyword in Javascript that refers to the executing environment of the function:

  • If you execute a function in the global scope, this will be bound to the window
  • If you pass the function to a callback for an event handler, this will be bound to the DOM element that raised the event

Binding

The bind method basically says, when you call the function, replace this with whatever my argument is. So, for example:

let a = {}
function test_this() {
     return this === a;
}  

test_this(); // false
test_this.bind(a)(); // true (.bind() returns the bound function so we need to call the bound function to see the result)

Additionally arrow functions are simply syntactic sugar for binding the function’s this to the current value of this. For example,

let b = () => { /* stuff */ }

is the same as

let b = (function () { /* stuff */}).bind(this);

(basically, I know this is an oversimplication)

Your predicament

In the normal course of events (not using arrow functions), this is bound to the DOM element.

When you’re executing the creation of the event handler input.addEventListener('change', handleUpdate.bind(this)); you’re running in the global scope (so this === window). So you’re effectively running input.addEventListener('change', handleUpdate.bind(window)); (which is the behavior you’re noticing). And using the arrow function is the same thing.

If you want to replace the callback with an anonymous function you should instead do:

const handleUpdate = function (e) {
  const that = e.target;
  const newValue = `${that.value}${that.dataset.sizing || ''}`;
  // etc.
}

Leave a Comment