DEV Community

Aditya Singh
Aditya Singh

Posted on

Call, Apply and Bind

๐Ÿ’ก In JavaScript, call, apply and bind are three methods that are used to manipulate the โ€˜thisโ€™ context in a particular function.

First let me create a simple object to explain this:

var person = {
    name : "john",
    hello: function(thing){
        console.log(this.name+ " says hello "+ thing);
    }
}

person.hello("world"); //john says hello world
Enter fullscreen mode Exit fullscreen mode

Call, apply and bind allow us to explicitly set the execution context for the this keyword

call

It is used to invoke a function with specified this value and individual arguments. The syntax is:

functionName.call(thisArg, arg1, arg2, ...);

var person = {
    name : "john",
    hello: function(thing){
        console.log(this.name+ " says hello "+ thing);
    },
};

var alterEgo = {
  name: "Rose"
};

person.hello.call(alterEgo, "world"); //Rose says hello world
Enter fullscreen mode Exit fullscreen mode

apply

It works same as Call method, but here we take array of all our parameters.

for example:

var person = {
    name : "john",
    hello: function(thing){
        console.log(this.name+ " says hello "+ thing);
    },
};

var alterEgo = {
  name: "Rose"
};

person.hello.call(alterEgo, ["world"]); //Rose says hello world
Enter fullscreen mode Exit fullscreen mode

bind

It works the same as call , but instead of executing the function, it returns a new function that can be executed later. The syntax is:

var newFunction = functionName.bind(thisArg, arg1, arg2, ...);

Enter fullscreen mode Exit fullscreen mode
var person = {
    name : "john",
    hello: function(thing){
        console.log(this.name+ " says hello "+ thing);
    },
};

var alterEgo = {
  name: "Rose"
};

var helloRose = person.hello.bind(alterEgo, "world");
helloRose(); //Rose says hello world
Enter fullscreen mode Exit fullscreen mode

Top comments (0)