Binding of ‘this’ in Javascript

In JavaScript, the ‘this’ keyword plays a crucial role in determining the context within which a function is executed. Understanding and effectively managing ‘this’ is important for writing clean and maintainable code in JS. In this blog, we will dive deep into the concept of ‘this’ and explore various techniques for binding it in different scenarios. Here, We are going to explain- what are the ways of javascript this binding. We will start from basics which means you first need to understand what is binding in Javascript. By the end, you will have a clear understanding of how ‘this’ works and be equipped with the knowledge to control its behavior in your JavaScript applications.

What is Binding?

Binding in JavaScript (Javascript bind) describes the process of connecting a value to a specific variable or function. It determines the scope and accessibility of variables and the behavior of functions. In simple terms, It determines how the ‘this’ keyword behaves within a function and allows you to control the value of ‘this’ when the function is called. Binding is important because it influences how functions access and interact with variables, properties, and methods within different contexts.

What is ‘this’ keyword in JS?

In JavaScript, the ‘this’ keyword plays a crucial role in determining the context within which a function is executed. it refers to the object that owns or calls the currently executing function. Its value is dynamically determined at runtime based on the invocation context. Below we have mentioned the ways of ‘this’ binding in javascript.

Ways of Binding ‘this’ Keyword in JS

There are different ways of binding ‘this’ in js.

1. Implicit Binding

The most common way for ‘this’ keyword to be bound is implicity. Implicit binding is the best method of binding this in javascript. This happens when a function is called a method of an object. In this case, ‘this’ will refer to the object that the function is called on. and it is automatically done by the JS engine.

Here’s an example:

In the above example, ‘Person’ is the context, and when ‘sayName()’  function is called on the ‘Person’ object, ‘this’ refers to the whole object that is the ‘Person’ object. 

2. Explicit binding

Explicit binding is yet another way of binding this in javascript. The ‘this’ keyword can also be bound explicitly. If You want to explicitly specify the ‘this’ value for a function,  then this technique is used. It can be done using the call(), apply(), or bind() methods.

1. The call() method takes a list of arguments, and it binds ‘this’ to the first argument.

           Here’s an example:

In the above example, call() is used to invoke the ‘fun()’ function with the ‘this’ value set to the ‘person’ object. This allows us to access the ‘name’ property of the ‘person’ object within the ‘fun’ function.

We can also pass additional arguments to the function using call() :

Here, the second argument of ‘call()’ is used to pass the message argument to the ‘call()’ function.

2. The apply() method is similar to the call() method, but it takes an array of arguments instead of a list of arguments.

Here’s an example:

In the above example, apply() is used to invoke the ‘fun()’ function with ‘this’ value set to the ‘person’ object. The ‘message’ array is passed as the second argument, which is then spread into individual arguments for the ‘fun()’ function.

3. The javascript bind() methods creates a new function with a bound ‘this’ value and any additional arguments provided. The original function is not modified.

  Here’s an example:

In  the above example, bind() is used to create a new function ‘greetPerson’ with ‘this’ value set to the ‘person’ object. The ‘greetPerson’ function can be invoked separately. We can also present arguments using bind().

3. Using ‘new’ Keyword

When a function is used with the ‘new’ keyword, it is called as a constructor function and ‘this’ keyword inside the function is bound to the newly created object. This means that any references to ‘this’ inside the function will refer to the new object.

Here’s an example:

In the above example, The ‘this’ keyword inside ‘car’ function will refer to the ‘myCar’ object, so the make, model, and year properties will be set on the myCar object.

4. Default Binding

in javaScript, when a function is called without any special syntax, ‘this’ refers to the global object. In a browser, the global object is window.

Here’s an example:

In the above example, ’this’ keyword is not resolved with any of the bindings, implicit , explicit, or  ‘new’, then the ‘this’ is bound to the window(global) object.

Conclusion

Understanding the concept of binding and knowing how to control the behavior of ‘this’ is crucial in JavaScript to ensure the proper functioning and avoid unexpected results when working with functions and objects. Above, we have explained the binding in Javascript of “this” keyword. Here are the highlights of the same:

  • 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, ‘this’ keyword inside the function binds to the new object being constructed.
  • When the ‘this’ keyword is not resolved with any of the bindings, implicit, explicit, or new, then this is bound to the window(global) object. In JavaScript’s strict mode, this will be undefined.

Recent Post

  • How to Implement In-Order, Pre-Order, and Post-Order Tree Traversal in Python?

    Tree traversal is an essential operation in many tree-based data structures. In binary trees, the most common traversal methods are in-order traversal, pre-order traversal, and post-order traversal. Understanding these tree traversal techniques is crucial for tasks such as tree searching, tree printing, and more complex operations like tree serialization. In this detailed guide, we will […]

  • Mastering Merge Sort: A Comprehensive Guide to Efficient Sorting

    Are you eager to enhance your coding skills by mastering one of the most efficient sorting algorithms? If so, delve into the world of merge sort in Python. Known for its powerful divide-and-conquer strategy, merge sort is indispensable for efficiently handling large datasets with precision. In this detailed guide, we’ll walk you through the complete […]

  • Optimizing Chatbot Performance: KPIs to Track Chatbot Accuracy

    In today’s digital age, chatbots have become integral to customer service, sales, and user engagement strategies. They offer quick responses, round-the-clock availability, and the ability to handle multiple users simultaneously. However, the effectiveness of a chatbot hinges on its accuracy and conversational abilities. Therefore, it is necessary to ensure your chatbot performs optimally, tracking and […]

  • Reinforcement Learning: From Q-Learning to Deep Q-Networks

    In the ever-evolving field of artificial intelligence (AI), Reinforcement Learning (RL) stands as a pioneering technique enabling agents (entities or software algorithms) to learn from interactions with an environment. Unlike traditional machine learning methods reliant on labeled datasets, RL focuses on an agent’s ability to make decisions through trial and error, aiming to optimize its […]

  • Understanding AI Predictions with LIME and SHAP- Explainable AI Techniques

    As artificial intelligence (AI) systems become increasingly complex and pervasive in decision-making processes, the need for explainability and interpretability in AI models has grown significantly. This blog provides a comprehensive review of two prominent techniques for explainable AI: Local Interpretable Model-agnostic Explanations (LIME) and Shapley Additive Explanations (SHAP). These techniques enhance transparency and accountability by […]

  • Building and Deploying a Custom Machine Learning Model: A Comprehensive Guide

    Machine Learning models are algorithms or computational models that act as powerful tools. Simply put, a Machine Learning model is used to automate repetitive tasks, identify patterns, and derive actionable insights from large datasets. Due to these hyper-advanced capabilities of Machine Learning models, it has been widely adopted by industries such as finance and healthcare.  […]

Click to Copy