JavaScript: call(), apply(), and bind()


What Are They?

These methods let you control the this context (i.e., what this refers to) inside a function.

They are used when you want to borrow methods or invoke a function with a specific this value.



Example Setup:

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

function greet(greeting, punctuation) {
  console.log(`${greeting}, ${this.name}${punctuation}`);
}


call()

  • Calls the function immediately
  • Takes arguments individually
greet.call(person, "Hello", "!"); // Output: Hello, Alice!
              


apply()

  • Calls the function immediately
  • Takes arguments as an array
greet.apply(person, ["Hi", "!!"]); // Output: Hi, Alice!!
              


bind()

  • 🔹 Returns a new function with this bound
  • 🔹 Does NOT execute the function immediately
const sayHello = greet.bind(person, "Hey", "...");
sayHello(); // Output: Hey, Alice...


Use Case: Borrowing Methods

const user1 = {
  name: "John",
  printName: function () {
    console.log(this.name);
  },
};

const user2 = {
  name: "Emma",
};

user1.printName.call(user2); // Output: Emma


Real-World Scenario: Math.max

const numbers = [5, 10, 2, 8];

const max = Math.max.apply(null, numbers);
console.log(max); // Output: 10
  • apply() spreads the array as individual arguments.
  • null means no specific this context is needed.


Difference Summary

Method Executes Immediately? Arguments Passed As Returns New Function?
call() Yes Individual args No
apply() Yes Array No
bind() No Individual args Yes


Bonus: bind() for Callbacks

const obj = {
  count: 0,
  increment() {
    this.count++;
    console.log(this.count);
  },
};

setTimeout(obj.increment.bind(obj), 1000); // Output: 1

Without bind(), this would be undefined in strict mode!