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)