JavaScript's this keyword is one of the hardest aspects of the language to grasp. But it is critically important for writing more advanced JavaScript code.
In JavaScript, the this keyword allows us to:
- Reuse functions in different execution contexts. It means, a function once defined can be invoked for different objects using the
thiskeyword. - Identifying the object in the current execution context when we invoke a method.
The this keyword is very closely associated with JavaScript functions. When it comes to this, the fundamental thing is to understand where a function is invoked. Because we don't know what is in the this keyword until the function is invoked.
The usage of this can be categorized into five different binding aspects. In this article, we will learn about all five aspects with examples.
- There are three very special methods,
call(),apply()andbind()that help us achieve explicit binding.
In Summary
To summarize,
- In the case of implicit binding,
thisbinds to the object adjacent to the dot(.) operator while invoking the method. - In the case of explicit binding, we can call a function with an object when the function is outside of the execution context of the object. The methods
call(),apply(), andbind()play a big role here. - When a function is invoked with the
newkeyword, thethiskeyword inside the function binds to the new object being constructed. - When the
thiskeyword is not resolved with any of the bindings,implicit,explicitornew, thenthisis bound to thewindow(global)object. In JavaScript's strict mode,thiswill be undefined. - In HTML event handlers,
thisbinds to the HTML elements that receive the event.
There is one more case where this behaves differently, such as with ES6 arrow functions. We will take a look at that in a future article.
No comments:
Post a Comment