jsnotes

Topic 012: Call, Apply and Bind in JS

Topic 012: Call, Apply and Bind in JS

In JavaScript, call, apply, and bind are methods that allow you to control the context (this value) within which a function is executed. Here’s an explanation of each with examples:

call Method

The call method calls a function with a given this value and arguments provided individually.

Example:

function greet(greeting, punctuation) {
  console.log(greeting + ", " + this.name + punctuation);
}

const person = {
  name: "Alice",
};

greet.call(person, "Hello", "!"); // Output: Hello, Alice!

apply Method

The apply method calls a function with a given this value and arguments provided as an array (or an array-like object).

Example:

function greet(greeting, punctuation) {
  console.log(greeting + ", " + this.name + punctuation);
}

const person = {
  name: "Bob",
};

greet.apply(person, ["Hi", "!!"]); // Output: Hi, Bob!!

bind Method

The bind method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Example:

function greet(greeting, punctuation) {
  console.log(greeting + ", " + this.name + punctuation);
}

const person = {
  name: "Charlie",
};

const greetPerson = greet.bind(person, "Hey");
greetPerson("!!!"); // Output: Hey, Charlie!!!

Without Effect (Using Global this)

When these methods are not used, this refers to the global object (in non-strict mode) or undefined (in strict mode).

Example:

function greet(greeting, punctuation) {
  console.log(greeting + ", " + this.name + punctuation);
}

global.name = "Global"; // In browser environment, use `window.name = 'Global';`
greet("Hello", "!"); // Output: Hello, Global!

Summary