.call(), .bind(), .apply() Differences in JS

Sraban Pahadasingh    June 25, 2024 12:23 AM

Certainly! Understanding the differences between .call(), .apply(), and .bind() is crucial for effective JavaScript development. They all serve the purpose of function invocation with a specific context (this value), but they differ in their usage and application.

.call()

Calls a function with a specified this value and individual arguments.

  • Invokes the function immediately.
  • Allows you to pass arguments individually.
  • Useful when you need to call a function with a specific this value and arguments.
  • Example:

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

    greet.call(null, 'Hello', 'Alice'); // Output: Hello, Alice

.apply()

Similar to .call(), but takes an array of arguments.

  • Invokes the function immediately.
  • Allows you to pass arguments as an array.
  • Handy when the arguments are already in an array or array-like structure.

  • Example:

    greet.apply(null, ['Hello', 'Alice']); // Output: Hello, Alice

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

    showThis.call({ name: 'Bob' }); // Output: { name: 'Bob' }
    showThis.apply({ name: 'Bob' }); // Output: { name: 'Bob' }

.bind()

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

  • Does not invoke the function immediately.
  • Creates a new function with a bound this value and optionally, pre-set arguments.
  • Useful for creating a new function that can be called later with the specific this context.

    • Example:

    const greetAlice = greet.bind(null, 'Hello', 'Alice');
    greetAlice(); // Output: Hello, Alice

    const person = {
      name: 'Alice',
      showThis() {
        console.log(this);
      }
    };

    const boundShowThis = person.showThis.bind({ name: 'Bob' });
    boundShowThis(); // Output: { name: 'Bob' }

Summary Table

Feature .call() .apply() .bind()
Invocation Immediate Immediate Delayed (returns new function)
Arguments Individual (arg1, arg2, ...) Array ([arg1, arg2, ...]) Individual (arg1, arg2, ...)
this Binding Immediate, changes this context Immediate, changes this context Delayed, changes this context for the new function
Use Case Borrowing methods, invoking with a different this Functions expecting arguments as arrays Event handlers, preserving this context





Comments powered by Disqus