How to access the correct `this` inside a callback with example in JavaScript
Last updated:20th Jan 2023
In JavaScript, when a function is used as a callback, the value of this can be different than what is expected. To ensure that the correct value of this is used inside the callback, there are several ways to access it:
- Use the
bind()
method: Thebind()
the method creates a new function with thethis
value bound to the specified object.
let obj = {
name: 'My object',
myMethod: function() {
console.log(this.name);
}
};
setTimeout(obj.myMethod.bind(obj), 1000);
- Use the
call()
orapply()
method: Thecall()
andapply()
methods allow you to explicitly set the value ofthis
inside a function.
let obj = {
name: 'My object',
myMethod: function() {
console.log(this.name);
}
};
setTimeout(function() {
obj.myMethod.call(obj);
}, 1000);
- Use an arrow function: Arrow functions do not have their own
this
, they inherit it from the parent scope, so you can usethis
inside an arrow, function to access the samethis
as the parent function.
let obj = {
name: 'My object',
myMethod: function() {
setTimeout(() => {
console.log(this.name);
}, 1000);
}
};
obj.myMethod();
- Use
let that = this
inside the outer function and use it inside the callback function.
let obj = {
name: 'My object',
myMethod: function() {
let that = this;
setTimeout(function(){
console.log(that.name);
}, 1000);
}
};
obj.myMethod();
By using one of these methods, you can ensure that the correct value of this
is used inside the callback function.