DEV Community

Cover image for 🧠 How to access the correct `This` inside a callback
Ali Boukaroui
Ali Boukaroui

Posted on

🧠 How to access the correct `This` inside a callback

For more useful content, please follow me on @aliboukaroui

This is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined.

❌ Don't use This

You actually don't want to access This in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are 'self' and 'that'.

Alt Text

✅ How to refer to the correct this

👉 Use arrow functions 👈

ECMAScript 6 introduced arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable.

Alt Text

Top comments (0)