addEventListener - Difference between 2 ways of using callback functions as below

I’ve found 2 ways of using callback function in addEventListener and confused what each does ?

In first option why don’t we use parenthesis ?

Both cartLogic and clearCart are part of same class

Please clarify in detail

Option 1

cartLogic() {
    clearCartBtn.addEventListener('click', this.clearCart);
}

Option 2:

cartLogic() {
        clearCartBtn.addEventListener('click', () => {
            this.clearCart();
           })
}

this inside of the clearCart method for the first one will refer to the button(the event target/what triggered the event). addEventListener binds this to the element - the button in this case

in the second option, this will refer to the class/object because arrow functions do not know the word this - clearCart was executed inside of an arrow function so this will refer to what it would normally refer to.

Alternatively, you could use clearCartBtn.addEventListener('click' , this.clearCart.bind(this)). That will bind what the word this will refer to in the method being called to the class/object.

Since they are in the same class, you could have also created the method being called with an arrow function (arrow func don’t know this). But that means any object created based on that class will have that method directly in it and not in it’s prototype.

2 Likes

If you want to get some more in-depth knowledge about this, I can recommend Kyle Simpson’s book on this.

1 Like

Not really sure your actual question was answered.

Because that would run the function immediately.

Event handlers are always given a callback, you never run the function/method but just pass it to be called later by the handler when the event is triggered (e.g. a click).

In the first code, the method is passed as a callback, in the second code an anonymous function is passed as the callback and when it gets invoked it will run the code inside it. The method inside the anonymous function has to be invoked, hens the parentheses. If the method inside the anonymous function didn’t have parentheses it would not run when the anonymous function was called by the handler.

Also, my guess would be that the method was bound in the constructor.

1 Like