DEV Community

Aditya Singh
Aditya Singh

Posted on

1

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

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay