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

  • A Comprehensive Guide to Sentiment Analysis Using NLP

    Businesses need to understand public interests, attitudes, behavior, and trigger points in today’s dynamic and competitive market. This enables them to efficiently serve their customers, grab opportunities, grow, and develop resilience in the face of a constantly shifting market. Many businesses find it challenging to process vast amounts of text-based data in order to get […]

  • How AI Is Revolutionizing Banking: Transforming Customer Experiences and Enhancing Financial Security

    Banking is a huge industry with a global Banking market likely to achieve a Net Interest Income of USD 10.34 trillion, with Traditional Banks holding a huge stake of USD 8.30 trillion. According to Statista’s projections suggest an annual growth rate of 4.82% (CAGR 2024-2028), culminating in a market volume of USD12.48 trillion by 2028. […]

  • Mastering Hyperparameter Tuning in Python: Strategies, Techniques, and Tools for Model Optimization

    Understanding various aspects of deep learning and machine learning can often feel like stepping into uncharted territory with no clue where to go. As you start exploring various algorithms and data, you realize that success is based on more than just building a raw model, it’s more about fine-tuning it to perfection. And when we […]

  • What is Transfer Learning? Exploring The Popular Deep Learning Approach

    Have you ever thought about how quickly your smartphone recognizes faces in photos or suggests text as you type? Behind these features, there’s a remarkable technique called Transfer Learning that expands the capabilities of Artificial Intelligence. Now you must be wondering- What is Transfer Learning ? Picture this: Instead of starting from the square from […]

  • LLMOps Essentials: A Practical Guide To Operationalizing Large Language Models

    When you engage with ChatGPT or any other Generative AI tool, you just type and enter your query and Tada!! You get your answer in seconds. Ever wondered how it happens and how it is so quick? Let’s peel back the curtain of the LLMs a bit. What actually happens behind the screen is a […]

  • Building Intelligent AI Models For Enterprise Success: Insider Strategies 

    Just picture a world where machines think and learn like us. It might sound like a scene straight out of a sci-fi movie, right? Well, guess what? We are already living in that world now. Today, data, clever algorithms, and AI models are changing the way businesses operate. AI models are serving as a brilliant […]

Click to Copy