Wednesday, October 19, 2022

The JavaScript `this` Keyword + 5 Key Binding Rules Explained for JS Beginners

 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 this keyword.
  • 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.

  1. There are three very special methods, call()apply() and bind() that help us achieve explicit binding.

In Summary

To summarize,

  • In the case of implicit binding, this binds 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(), and bind() play a big role here.
  • When a function is invoked with the new keyword, the this keyword inside the function binds to the new object being constructed.
  • When the this keyword is not resolved with any of the bindings, implicitexplicit or new, then this is bound to the window(global) object. In JavaScript's strict mode, this will be undefined.
  • In HTML event handlers, this binds 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