Skip to content
jshacks.dev
Functions

How to Bind this in Event Handlers

Fix a lost this in JavaScript event handlers with arrow functions, bind(), class fields and handleEvent, and see which one removes listeners correctly.

7 min read
Summarize in AI
Flat illustration of one event fanning out to several listeners, with the JavaScript, Google Chrome, Socket.io and Node.js logos.

You write a class with a method, pass the method to addEventListener, and the click handler fails with "Cannot read properties of undefined". The method is the same code that worked a line earlier when you called it directly. What changed is how it was called, because in JavaScript the value of this depends on the call, not on where the function was defined. When the browser calls your listener, it supplies its own this. This post explains why that happens and shows the four ways to fix it, with their trade-offs, including the one that matters for removing listeners. Samples run in current browsers and in Node.js 24 with a small stand-in for the DOM.

Why this is lost

this is set by the call site. counter.increment() calls the function with this equal to counter. Pulling the method out of the object and calling it alone, as an event system does, leaves nothing to supply this.

JavaScript
class Counter {
  count = 0;

  increment() {
    this.count += 1;
    return this.count;
  }
}

const counter = new Counter();
const { increment } = counter;

console.log(counter.increment());

try {
  increment();
} catch (error) {
  console.log(error.name);
}
Text
1
TypeError

The first call works, because the object is on the left of the dot. The second passes undefined as this: class bodies are always strict mode, so there is no fallback to the global object, and this.count throws a TypeError. An event listener is the same case. button.addEventListener("click", counter.increment) hands over the function and nothing else.

When a regular function is called by the browser as an event listener, this is the element the listener is attached to (strictly, event.currentTarget). That is why the failure message is often about a missing property on a DOM element, not about undefined: this is the button, and the button has no count.

A stand-in for the DOM

To keep the samples runnable in Node.js 24, we use EventTarget and Event, which are globals in Node.js and share their listener behavior with the browser. In a browser, replace target with a real element.

JavaScript
const target = new EventTarget();

class Logger {
  prefix = "log";

  handle(event) {
    return `${this.prefix}: ${event.type}`;
  }
}

const logger = new Logger();

target.addEventListener("ping", function (event) {
  console.log(this === target);
});

target.dispatchEvent(new Event("ping"));
Text
true

For a regular function, this inside the listener is the target. That is the behavior your class method collides with.

Fix 1: an arrow function at the call site

An arrow function does not have its own this. It uses the one from the surrounding scope, so wrapping the call in an arrow keeps the object as the receiver.

JavaScript
class Button {
  label = "save";

  constructor(target) {
    target.addEventListener("click", (event) => this.onClick(event));
  }

  onClick(event) {
    return `${this.label} ${event.type}`;
  }

  report(event) {
    console.log(this.onClick(event));
  }
}

const buttonTarget = new EventTarget();
const button = new Button(buttonTarget);

buttonTarget.addEventListener("click", (event) => button.report(event));
buttonTarget.dispatchEvent(new Event("click"));
Text
save click

Inside the arrow function, this is the Button instance created by the constructor, so this.onClick(event) is a normal method call. The cost is that you have created an anonymous function. You cannot pass it to removeEventListener later, because removal needs the same function reference, and a fresh arrow function is a different one.

Fix 2: bind()

fn.bind(obj) returns a new function whose this is fixed to obj, whatever the call.

JavaScript
class Toggle {
  on = false;

  flip() {
    this.on = !this.on;
    return this.on;
  }
}

const toggle = new Toggle();
const flip = toggle.flip.bind(toggle);

console.log(flip(), flip(), flip());
Text
true false true

A bound function ignores any this the caller tries to supply. Binding returns a new function every time, so if you want to remove the listener later, store the bound result.

JavaScript
class Widget {
  clicks = 0;

  constructor(target) {
    this.target = target;
    this.handleClick = this.handleClick.bind(this);
    target.addEventListener("click", this.handleClick);
  }

  handleClick() {
    this.clicks += 1;
  }

  destroy() {
    this.target.removeEventListener("click", this.handleClick);
  }
}

const widgetTarget = new EventTarget();
const widget = new Widget(widgetTarget);

widgetTarget.dispatchEvent(new Event("click"));
widget.destroy();
widgetTarget.dispatchEvent(new Event("click"));

console.log(widget.clicks);
Text
1

The constructor replaces this.handleClick with a bound copy, an own property that shadows the prototype method. The same reference goes to addEventListener and removeEventListener, so destroy() really detaches the listener, and the second click does nothing. If you called this.handleClick.bind(this) in both places, the two functions would differ and the removal would silently fail.

Fix 3: arrow functions as class fields

A class field initialized with an arrow function gives each instance its own bound method, without a constructor line.

JavaScript
class Panel {
  open = false;

  toggle = () => {
    this.open = !this.open;
    return this.open;
  };
}

const panel = new Panel();
const { toggle } = panel;

console.log(toggle(), toggle());
Text
true false

Inside the field initializer, this is the new instance, and the arrow function captures it. You can now pass panel.toggle anywhere. The trade-off is that the method is not on the prototype: every instance carries its own function object, memory grows with the number of instances, and subclasses cannot call super.toggle() because there is no prototype method to reach. For a component with a handful of instances this is fine. For thousands of small objects, prefer a prototype method with bind where it is needed.

Fix 4: handleEvent

There is a way to avoid binding altogether. addEventListener accepts an object with a handleEvent method instead of a function, and the browser calls that method with this set to the object.

JavaScript
class Tracker {
  seen = [];

  handleEvent(event) {
    this.seen.push(event.type);
  }
}

const trackerTarget = new EventTarget();
const tracker = new Tracker();

trackerTarget.addEventListener("open", tracker);
trackerTarget.addEventListener("close", tracker);

trackerTarget.dispatchEvent(new Event("open"));
trackerTarget.dispatchEvent(new Event("close"));
trackerTarget.removeEventListener("open", tracker);
trackerTarget.dispatchEvent(new Event("open"));

console.log(tracker.seen);
Text
[ 'open', 'close' ]

The object is the listener, so adding and removing use the same reference with no extra work, and one handleEvent can serve several event types by checking event.type. The pattern is part of the DOM specification, it works in browsers and in Node.js EventTarget, and it is underused. It does not fit when you want several separate methods, and a reader who has not seen it may find it odd.

The arrow function trap with this

One more situation catches people. An arrow function used as a method of an object literal does not get the object as this, because the arrow takes this from the scope where the literal was written.

JavaScript
const widget = {
  name: "panel",
  regular() {
    return this?.name;
  },
  arrow: () => typeof this,
};

const detached = widget.regular;

console.log(widget.regular());
console.log(detached());
console.log(widget.arrow());
Text
panel
undefined
undefined

The first call has the object on the left of the dot, so this is widget. The second is detached and runs in a module or function in strict mode, so this is undefined, and the optional chain returns undefined instead of throwing. In the third, the arrow reads this from the outer scope, which is the top level of the module. In an ES module, which these samples assume because they use top-level await, that is undefined, so typeof this is the string "undefined". In a CommonJS file it would be module.exports. The practical rule is to use arrow functions for callbacks that should keep the surrounding this, and method syntax for functions that should receive the object they are called on.

Frameworks that bind for you

Most component frameworks solve this at their own layer, and it is worth knowing what yours does before you add bind calls. Template syntax in Vue, Angular and Svelte calls handlers with the component as the receiver, so a method reference in a template just works. React function components have no this at all, since handlers are closures over props and state. Only plain DOM code and class-based React components need the fixes in this post. Adding bind where the framework already handles it is harmless, and it hides the real reason the code works.

Which one to choose

For a one-off listener that you never remove, an arrow function at the call site is the shortest and clearest. When you need to remove the listener, keep a reference: either bind once in the constructor, as Widget does, or use a class field arrow. When one object handles many events, handleEvent is the cleanest. Avoid calling bind inside addEventListener(...) and again in removeEventListener(...): it looks right and does nothing.

Another way to get cleanup without keeping references is an AbortSignal. Pass { signal } as the third argument, and aborting the controller removes every listener registered with it.

JavaScript
const signalTarget = new EventTarget();
const controller = new AbortController();
let hits = 0;

signalTarget.addEventListener("tick", () => (hits += 1), { signal: controller.signal });

signalTarget.dispatchEvent(new Event("tick"));
controller.abort();
signalTarget.dispatchEvent(new Event("tick"));

console.log(hits);
Text
1

The signal option is supported by EventTarget in current browsers and in Node.js, and it works with anonymous arrow functions, which makes it the neatest way to clean up listeners that capture this through an arrow.

Also inBrowser
Taggedthis
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.