Aashman Verma
Aashman Verma's Blog

Follow

Aashman Verma's Blog

Follow
call(), apply(), bind() in Javascript

call(), apply(), bind() in Javascript

Aashman Verma's photo
Aashman Verma
ยทFeb 11, 2023ยท

2 min read

Play this article

.call()

In JavaScript, the "call" method allows you to invoke a function and set the value of this within the context of the function. This means that you can specify the object that should be considered as the this the value inside the function, instead of using the default value (which is typically either the global object or undefined).

Here's an example to demonstrate the use of call:

const obj = {
    name : "Harry",
    greet : function (greet) {
        console.log(`${greet} ${this.name}`);
    }
}
obj.greet("hi"); // returns hi harry 
// what if we want to change the this instance for a new object we can use 
const obj1 = {
    name : "Joe",
}
obj.greet.call(obj1, "welcome"); // returns welcome Joe

By using the call() method the first parameter is the instance that we specified to obj1, then we passed the parameter required by the function to work.

Similarly, we can specify this keyword in the function and then change this instance with the help of the call() method.

.apply()

The "apply" method is similar to the "call" method, but instead of passing individual arguments to the function, it takes an array of arguments.

const obj = {
    name : "Harry",
    greet : function (greet, post) {
        console.log(`${greet} ${this.name}, ${post}`);
    }
}
obj.greet("hi","chairpersor"); // returns hi harry, chairperson
// what if we want to change the this instance for a new object we can use 
const obj1 = { name : "Joe" }
obj.greet.apply(obj1,["welcome","leader"]); // returns welcome Joe, leader

Here we passed the first argument our this keyword and in the second argument we passed the array of parameters. This method can be used when we have multiple parameters used in our function.

.bind()

It works just the same as .call() method, the only difference is that the bind() method returns a new function that can be stored for a particular type of function.

const obj = {
    name : "Harry",
    greet : function (greet) {
        console.log(`${greet} ${this.name}`);
    }
}
obj.greet("hi"); // returns hi harry 
const obj1 = { name : "Joe" }
const welcomeJoe = obj.greet.bind(obj1, "welcome");
const byeJoe = obj.greet.bind(obj1, "bye");
welcomeJoe(); // returns welcome Joe
byeJoe(); // returns bye Joe

Here we used the .bind() method to create a specific function welcomeJoe and byeJoe which is fixed every time we call the function it gives the same output.


Follow -

Follow me for more such content you can visit the series on my profile for more js blogs. ๐Ÿ˜€

ย 
Share this