How to Access the Correct 'this' Inside a JavaScript Callback?
- Use ES6 arrow functions:
One of the simplest ways to access the correct “this” inside a callback is to use ES6 arrow functions. Arrow functions are essentially anonymous functions that don’t change the value of “this” and always point to the outer lexical scope. This means that you don’t have to worry about using call or apply to bind the function to the object.
Here’s an example:
class Foo {
constructor() {
this.bar = 'bar';
}
doStuff() {
setTimeout(() => {
console.log(this.bar);
});
}
}
- Use the bind() method:
If you don’t prefer to use ES6, another alternative is the “bind()” method that you can use to bind the function to a specific object. With bind(), you’re creating a new function from an existing one while also setting the “this” keyword to the desired value. Here’s an example:
const obj = {
x: "Hello There",
foo() {
console.log(this.x)
}
}
setTimeout(obj.foo.bind(obj), 1000);
- Store “this” in a variable:
Another method is to store the required value of “this” in a variable outside the callback and then reference that variable inside the callback. Here’s an example:
class Foo {
constructor() {
this.bar = 'bar';
const self = this;
setTimeout(function() {
console.log(self.bar);
}, 1000);
}
}
- Use the call() or apply() method:
The call and apply methods invoke a function with a specified this value. apply accepts an array of arguments, while call accepts arguments separately. Wrap the call in a callback so it runs after the delay:
const obj = {
x: "Welcome to the blog.",
foo() {
console.log(this.x);
}
}
setTimeout(() => obj.foo.call(obj), 1000);
- Use callbacks designed specifically to solve this issue:
jQuery provides $.proxy to bind a function to an object. For new code, native bind is usually sufficient. Arrow functions capture this from their surrounding scope and cannot be rebound this way:
const obj = {
x: "Hello World",
foo() {
console.log(this.x);
}
}
setTimeout($.proxy(obj.foo, obj), 1000);
Conclusion:
Arrow functions capture the surrounding this. Use bind when you need to pass a regular method with a fixed receiver.