The scope of
this frequently gets overwritten. Let me give you a few examples of when
this changes based on scope and how to avoid any issues.
this will typically refer to the whole object, with all its member variables and methods. But as soon as one of your methods uses a callback function, for example, anything from a simple
setTimeout() to a
forEach(), the callback function overwrites
So let’s say we use
setTimeout() and need access to one of the object’s methods inside the callback function (which is the first parameter in setTimeout). The solution is what we have before:
var that = this;.
The whole code block might look like this:
Callback Functions in Iterative Functions
Another very common use case is iterative functions, like
forEach(). Each iteration calls a callback function, so again,
this gets overwritten inside the callback function’s scope.
Callback functions are very common in some libraries, like jQuery. jQuery ajax calls also overwrite
this. If you are in doubt, you can always
console.log(this); just to see what