How To Access “this” Inside a JavaScript Callback Function
Let’s address the confusing keyword once and for all
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…