How To Access “this” Inside a JavaScript Callback Function

Let’s address the confusing keyword once and for all

Johannes Baum
Better Programming

Toy figurine
Photo by Edo Nugroho on Unsplash.

The this keyword causes some confusion for many JavaScript programmers, especially those coming from other languages. A frequently asked question is how to access the correct this inside a callback function.

Consider the following code snippet:

The code is not resulting in the desired output. What is the problem here? Why is data behaving as intended, but this.data is not?

Well, the problem is that the value of this depends on where the function is executed. This is called runtime-binding. Every other variable’s value depends on where the function is defined.

The common misunderstanding in this example comes from the fact that many people assume this has the value that it had where the callback function was defined. The truth is, it will have a value depending on the context in which the callback function will be called. The this keyword is special in that sense. It behaves differently to other…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (1)

What are your thoughts?

Sneaky trick if working with events? Attach the object you want to mess with to the target of the event as a data- attribute.
That way when you want to access it, it's just event.currenTarget["data-whatever"] inside the event callback.
Technically…...

--