The Talent500 Blog
bind

Mastering Object-Function Binding in JavaScript Using the Bind Method

In my last blog post, I went deep into the call() method in JavaScript, breaking down how it’s used and showing examples of its syntax. However, I didn’t touch on the apply() method in that discussion. The apply() method is as easy as eating a piece of cake – just pass the arguments in the form of an array, and you’re done. Take a moment to check out that blog post, understand the call() method, and explore the differences between call() and apply() by playing around with arguments in array format.

Understanding the Issue

Now, let’s take a closer look at the problem. Below, you’ll find an object named “author“. This object has three properties, including a method.

const author = {

  name: “AJ”,

  topics: [“HTML”, “CSS”, “JS”, “React”],

  intro: function () {

    return `I’m ${this.name} and I write blogs on ${this.topics.join(“, “)}.`;

  },

};

 

So far, when we execute the “author.intro()” method, we get the expected result:

const authorIntro = author.intro();

console.log(authorIntro);

// Output: I’m AJ and I write blogs on HTML, CSS, JS, React.

However, what happens if we try to execute this “author.intro” method after one second using the “setTimeout()” function? Let’s find out.

setTimeout(author.intro, 1000);

Surprisingly, it throws an error: “Uncaught TypeError: Cannot read properties of undefined (reading ‘join’) at intro.”

The error occurs because, inside the “author” object, the “this” keyword now refers to the “window” object. Unfortunately, there is no “topics” array inside the window object, such as “window.topics.” Consequently, we encounter an error related to the “join()” method.

Now, let’s take a closer look at a potential syntax error. Consider the following code snippet:

const author = {

  name: “AJ”,

  topics: [“HTML”, “CSS”, “JS”, “React”],

  intro: function () {

    return `I’m ${this.name} and I write blogs on ${this.topics.join(“, “)}.`;

  },

};

// Incorrect usage

setTimeout(author.intro(), 1000);

At first glance, it may seem like this code will work as expected, but there’s a hidden syntax error. The issue lies in the way we are invoking the author.intro() method.

The author.intro() method is executed immediately, and its result (a string) is then passed to setTimeout. However, the setTimeout function expects a function reference as its first argument, not the result of a function call.

If we intend to delay the execution of the author.intro method by one second using setTimeout, we should pass a function reference, not the result of the function call.

Resolving the Issue

To overcome this problem, a common practice is to use a wrapper function as the callback for the setTimeout function. This allows us to then invoke the object method, ensuring that the this keyword refers to the “author” object. With this adjustment, the code works as expected.

const author = {

  name: “AJ”,

  topics: [“HTML”, “CSS”, “JS”, “React”],

  intro: function () {

    return `I’m ${this.name} and I write blogs on ${this.topics.join(“, “)}.`;

  },

};

setTimeout(() => {

  const authorIntro = author.intro();

  console.log(authorIntro);

}, 1000);

Alternatively, we can utilize the bind method in JavaScript, which is a method available on every function. This method allows us to explicitly set the this value for a function. Let’s take a closer look at this alternative solution in the next section.

Overview of the bind() method

The bind() method in JavaScript is a concept that allows developers to explicitly set the this value for a function, creating a new function with a fixed context. The primary purpose of bind() is to associate a function with a specific object, ensuring that when the function is invoked, this refers to that object.

The bind() returns a new function with the specified this value, without immediately executing the original function. Enough introduction. Let’s see the actual syntax of the bind() method.

Syntax of the bind() method

The bind() method in JavaScript is straightforward, but understanding its syntax is crucial for effective utilization. Below is a detailed breakdown of the bind() method syntax:

const boundFunction = originalFunction.bind(thisArg, arg1, arg2, );

The bind() method is called on the original function “originalFunction”, creating a new function “boundFunction” that is bound to a specific object according to the “thisArg”.

The thisArg is crucial because it defines what the this keyword inside the function will refer to when the bound function is called. It can be an object, a value, or null or undefined.

If additional arguments are provided (arg1, arg2, …), These are parameters that will be fixed in the newly created bound function. When the bound function is called, these arguments will be prepended to any arguments passed during the actual invocation.

Creating Bound Functions with bind()

In JavaScript, when we have an object and a function, and we want to ensure that the function’s this keyword refers to the specific object, we can create a bound function using the bind() method. Let’s walk through an example to understand this process.

Consider the following object and function:

const author = {

  name: “AJ”,

  topics: [“HTML”, “CSS”, “JS”, “React”],

};

function authorIntro(location) {

  return `I’m ${this.name} and I write blogs on ${this.topics.join(“, “)} from ${location}.`;

}

In this scenario, if we directly invoke authorIntro without binding, the this inside the function would refer to the global window object, potentially leading to errors when trying to access name and topics properties from the window object.

To ensure that the function is bound to the author object, we use the bind() method:

const boundFunction = authorIntro.bind(author);

console.log(boundFunction(“India”));

In our case, the bind() method is called on the function authorIntro. The first argument is the object to which the this value will be set when the bound function is called. Subsequent arguments (if any) are passed as parameters to the function.

The result of bind() is a new function boundFunction where the this context is guaranteed to be the specified object author.

The bound function can be invoked like any regular function. Additional arguments (e.g “India”) can be provided during the invocation, and they will be appended to the fixed parameters.

Different Ways to Invoke the bound function

When you create a bound function using the bind() method, there are various ways to invoke it. Here are common approaches, Some of them are:

  1. Separate Binding and Invocation:

const boundFunction = authorIntro.bind(author);

console.log(boundFunction(“India”));

  1. Direct Invocation in a Single Line:

console.log(authorIntro.bind(author)(“India”));

console.log(authorIntro.bind(author, “India”)());

Bound Function with setTimeout() method

When using the bind() method to create a bound function, it becomes particularly useful in scenarios like working with setTimeout(), where maintaining the correct this context is crucial. Let’s see the example:

const author = {

  name: “AJ”,

  topics: [“HTML”, “CSS”, “JS”, “React”],

};

function authorIntro(location) {

  console.log(`I’m ${this.name} and I write blogs on ${this.topics.join(“, “)} from ${location}.`);

return `I’m ${this.name} and I write blogs on ${this.topics.join(“, “)} from ${location}.`;

}

const boundFunction = authorIntro.bind(author, “India”);

setTimeout(boundFunction, 1000);

The boundFunction is created by binding authorIntro to the author object with the location set to India. This ensures that when boundFunction is invoked, the this context refers to the author object.

The setTimeout() function is then used, and boundFunction is passed as the callback function to be executed after a delay of 1000 milliseconds (1 second).

Thanks to the bind() method, there’s no need to wrap an object method inside another callback function. instead now the bind() method ensures that the this context is correctly set when boundFunction is invoked by the setTimeout function.

Conclusion

In conclusion, by creating a bound function using bind(), we ensure that the function operates within the desired context, enhancing predictability and reliability in our code. This concept becomes particularly useful in scenarios where the this value needs to be explicitly controlled.

Also, if you are looking for a JavaScript or React job, please search for them on Talent500.co

1+
Ajay Yadav

Ajay Yadav

I am a frontend developer and am eager to deep dive into the technologies through my content.

Add comment