Labs ICT
Pro Login

Call, Apply & Bind

Understanding the Problem

When a function is called as a method, this refers to the object it belongs to. When the function is extracted, this can change unexpectedly.

const person = {
  name: "Alice",
  greet: function() {
    console.log("Hello, I'm " + this.name);
  }
};

person.greet(); // Hello, I'm Alice

const greetFn = person.greet;
greetFn(); // Hello, I'm undefined (lost context)
Try it Yourself →

Using call

call invokes a function with a specific this value and arguments passed individually.

function introduce(city, country) {
  console.log(this.name + " from " + city + ", " + country);
}

const user = { name: "Bob" };
introduce.call(user, "Tokyo", "Japan");
// Bob from Tokyo, Japan

Using apply

apply is like call but arguments are passed as an array.

function sum(a, b, c) {
  return a + b + c + this.offset;
}

const context = { offset: 10 };
const args = [1, 2, 3];
console.log(sum.apply(context, args)); // 16

Using bind

bind returns a new function with this permanently set. It does not invoke the function.

const player = {
  name: "Alex",
  score: 0
};

function updateScore(points) {
  this.score += points;
  console.log(this.name + " scored! Total: " + this.score);
}

const playerUpdate = updateScore.bind(player);
playerUpdate(10); // Alex scored! Total: 10
playerUpdate(5);  // Alex scored! Total: 15

bind with Partial Application

bind can also pre-set arguments, creating partial functions.

function multiply(a, b) {
  return a * b;
}

const double = multiply.bind(null, 2);
const triple = multiply.bind(null, 3);

console.log(double(5)); // 10
console.log(triple(5)); // 15