JavaScript · Middle · Question 55 of 75

Why are event handlers often written as arrow-function class fields?

class Counter {
  count = 0;
  handleClick = () => { this.count++; };
}
button.addEventListener("click", counter.handleClick);

Explanation

A prototype method passed as a callback loses this. The trade-off: each instance gets its own copy of the function instead of sharing one on the prototype.

Further reading

Problem with a question

JavaScript · Middle · question 55

Test yourself

Take the JavaScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz