JavaScript EventListener and “this”

Andrew Park
2 min readJun 13, 2021

Not knowing what “this” referring to can cause a big headache in Object Oriented Programming in JavaScript.

In the example below, clicking on vote button should increase likes count (this.count) by one:

However, clicking on vote button cannot increment this.count. Why is that?

Well, I threw in a “debugger” in line line 15, and I tried again to see what “this” is referring to:

As you can see, within increaseLike() method, “this” is referring to “button” element, not instance object (like1). When an event is occurred (“click” event in this case), the DOM element on which the event occurred becomes “this”.

There are two ways to correct this:

(1). Change “increaseLike()” method into an arrow function:

This will work. However, one downside is that increaseLike() method becomes an instance method, and each instance of LikesCount class will carry around increaseLike() method (may not a good solution if a large number of instances will be created).

(2). Bind the EventListener within class constructor

Use regular function syntax, and in the class constructor, bind instance object to the EventListener. In this way, EventListener will have access to the instance object. Also, increaseLike() method becomes a prototype property of LikesCount class, not an instance method as first solution.

Even though solution 2 requires more key strokes, I think this is a better solution since each instance will not carry around same (increaseLike()) method.

Knowing what “this” is can be a real time saver. So, check on it often.

--

--