call, apply, and bind

call invokes a function immediately with a specified this and individual arguments. apply does the same but receives arguments as an array-like collection. bind does not invoke immediately; it creates a new function with a permanently bound this and optionally pre-filled arguments.

These methods are especially useful when adapting APIs, creating callbacks, or working with methods that need an explicit receiver.

Binding a Method
const user = {
  name: 'Suriya'
};

function greet(prefix) {
  return `${prefix}, ${this.name}`;
}

const greetUser = greet.bind(user, 'Hello');
console.log(greetUser());
💡 bind returns a new function. The new function uses user as this and pre-fills the prefix argument.
Key Takeaways
  • call invokes immediately with individual arguments.
  • apply invokes immediately with an argument collection.
  • bind returns a new function for later invocation.
Knowledge Check

Which method returns a new function instead of immediately invoking the original function?