JavaScript Course
JavaScript
/
Intermediate

call(), apply(), bind()

Definition

Three methods available on all JavaScript functions that allow you to explicitly dictate what the `this` keyword refers to when the function executes.

Explain Like I'm New

`call` is like calling an Uber and instantly telling the driver (the function) to go to a specific address (`this`). `apply` is the exact same, but you hand the driver an array of directions. `bind` doesn't call the Uber; it gives you a coupon for an Uber permanently locked to a specific address to use later.

Real World Example

Borrowing a method: using `Array.prototype.slice.call(nodeList)` to convert a DOM NodeList into a real JavaScript array.

Common Use Cases

  • •Borrowing methods from other objects
  • •Hard-binding `this` in class methods (React class components)

Interactive Example

const person1 = { name: 'Alice' };
const person2 = { name: 'Bob' };

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

// call: pass arguments by comma
greet.call(person1, 'Hello', '!'); // "Hello, Alice!"

// apply: pass arguments as an array
greet.apply(person2, ['Hi', '.']); // "Hi, Bob."

// bind: returns a NEW function to be called later
const greetAlice = greet.bind(person1);
greetAlice('Welcome', '!!!'); // "Welcome, Alice!!!"

Interview Questions

basic

  • What is the difference between `call` and `apply`?

intermediate

  • What does `bind` return?

advanced

  • Can you re-bind a function that has already been bound using `bind()`?

Flash Cards

Question

Call vs Apply?

Click to reveal answer
Answer

They execute the function immediately. `call` takes comma-separated arguments: `func.call(thisArg, a, b)`. `apply` takes an array of arguments: `func.apply(thisArg, [a, b])`.

Question

Can you re-bind a bound function?

Click to reveal answer
Answer

No. Once a function is bound using `.bind()`, its `this` context is permanently locked. Calling `.bind()` again on the returned function will have no effect.