Skip to main content

Command Palette

Search for a command to run...

The Magic of this, call(), apply(), and bind() in JavaScript

Updated
5 min read
The Magic of this, call(), apply(), and bind() in JavaScript

What is this in JavaScript

This is a keyword that is used to access code components in current execution context.

More formally...
In JavaScript, this is a special keyword that dynamically refers to the execution context — the object that is currently calling or owning the function. Its value is determined at runtime based on how a function is invoked, not where it is defined.

What is Current Execution Context ?

Current execution context is the context or more simply the environment in which the code is executing.

Lets now understand how this behaves differently inside normal functions and inside objects in JavaScript

this inside normal functions

When you call a normal function, there is no specific object calling it. By default, JavaScript assigns this to the global object (which is window in a web browser).

If you are using "strict mode" ('use strict'), JavaScript stops this default behavior, and this will simply be undefined.

function testingThis() {
  console.log(this); 
}

testingThis();

this inside objects

When a function is stored inside an object, it is called a method. When you call a method, the object sitting to the left of dot is the caller. Therefore, this becomes that object.

const bollywoodFilm = {
  name: "Bajirao Mastani",
  lead: "Ranveer",

  introduce() {
    return `\({this.lead} performs in \){this.name}`;
  },
};

console.log(bollywoodFilm.introduce());
// Output : Ranveer perfors in Bajirao Mastani

// Here value of this is 
// this = {
//            name: "Bajirao Mastani",
//            lead: "Ranveer",
//            introduce() {
//              return `\({this.lead} performs in \){this.name}`;
//            },
//  }

What call() does

The call() method executes a function immediately and allows you to manually state what this should be. Yes, you overwrite this using call. You can provide a custom this context according to which the function should react.

Syntax : You pass the new this context as the first argument, followed by any normal arguments the function needs, separated by commas.

Here is an example,

function reportDelivery(location, status) {
  return `\({this.name} at \){location}: ${status}`;
}

const deliveryBoy = { name: "Shobhit" };

console.log("Call: ", reportDelivery.call(deliveryBoy, "Nashik", "Ordered"));
// Outputs : Shobhit at Nashik: Ordered

What apply() does

The apply() method does the exact same thing as call()—it executes the function immediately and sets the this context.

The only difference is how you pass the arguments. Instead of passing them one by one separated by commas, you pass them together in a single array.

Syntax : function_name.call(newThisContext, [Array of Required Arguments])

Here is an example,

function reportDelivery(location, status) {
  return `\({this.name} at \){location}: ${status}`;
}

const deliveryBoy = { name: "Ansh" };

console.log("Apply: ", reportDelivery.apply(deliveryBoy, ["Mars", "Pick up"]));
// Output : Ansh at Mars: Pick up

Important Insight -> apply() is incredibly useful when you already have your data stored in an array and want to pass it into a function.

What bind() does

The bind() method does not execute the function immediately as Call() and Apply() do. Instead, it creates and returns a brand new function with this permanently locked to the object you provide. You can then store this new function and call it later.

Again the main functionality of bind() is You can then store this new function and call it later.

Here is an example,

function reportDelivery(location, status) {
  return `\({this.name} at \){location}: ${status}`;
}

const deliveryBoy = { name: "Ansh" };

console.log("Bind: ", reportDelivery.bind(deliveryBoy, "Haridwar", "WHAT"));

// Way 1 of using arguments
const bindReport = reportDelivery.bind(deliveryBoy,"Haridwar", "WHAT");
console.log(bindReport());
//Output : Aryan at Haridwar: Ordered

// Way 2
const bindReport = reportDelivery.bind(deliveryBoy,);
console.log(bindReport("Haridwar", "Ordered"));
//Output : Aryan at Haridwar: Ordered

Difference between call(), apply(), and bind()

Method

Execute's immediately?

How arguments provided?

Best used for...

call()

Yes

Individually (arg1, arg2)

Borrowing a method and passing a few known arguments.

apply()

Yes

As an Array ([arg1, arg2])

Borrowing a method when your arguments are already in a list/array.

bind()

No (Returns a new function)

Individually (arg1, arg2)

Saving a function with a locked-in context to be used later (like in event listeners or callbacks).

Test Your Skills (Assignment)

Try completing this short assignment in your code editor

  1. Create an object: Make an object called library with a name property (e.g., "City Library") and a method called printTicket that uses this.name to print a message (e.g., "Welcome to City Library").

  2. Borrow with call(): Create a second object called museum with just a name property. Use call() to borrow the library's printTicket method, but make it print the museum's name.

  3. Use apply() with arguments: Update the printTicket method to accept two parameters: visitorName and ticketNumber. Use apply() to call this method for the museum object, passing the visitor's name and ticket number inside an array.

  4. Use bind(): Use bind() to create a new, permanently bound function called printMuseumTicket that is locked to the museum object. Call this new function later in your code.

Summing Up

This is a important concept and can be overwritten using call, apply and bind methods.

Thanks for Reading...

More from this blog