When working with a regular function in JavaScript (not an arrow function), you'll find that when using the this context, you're referring to the object that invoked the function.
Sometimes, this ends up creating different results than what you'd expect.
Take the following example:
const Bob = {
temperature: "45 degrees"
sayNews() {
console.log('It is ${this.temperature} outside!')
}
}
setTimeout(Bob.sayNews, 1000) // It is undefined outside!
You'll notice that we get undefined for the temperature variable. That's because when we refer to this in our setTimeout call, we are actually referring to the Window Object itself, and NOT Bob.
Are you confused yet?
So let's break this down.
- setTimeout called on Bob
- Inside Bob, in the sayNews function,
thiswas referred to. - Since setTimeout is a Window Object method, Javascript thinks that
thisis referring to theWindow.
To fix this, we could do one of two things
Use .bind to specifically bind an object to a function
setTimeout(Bob.sayNews.bind(Bob) // It is 45 degrees outside!
Use arrow functions, introduced in ES6
setTimeout(() => Dug.sayHi(), 1000) // It is 45 degrees outside!
I hope this was helpful. Thanks for reading :)
Resources
Photo by Markus Spiske from Pexels
Top comments (2)
That was the easiest way to understand that.
Thanks Ralph, I'm glad it was helpful!