Lesson 62 +20 XP

Call, Apply, and Bind

Call, Apply, and Bind

These methods control what this refers to inside a function.

The problem

this usually refers to the owner of the function, but sometimes you want to choose the owner yourself.

call()

call runs a function and sets this:

const person = { name: "Ada" };

function greet(greeting) {
  console.log(greeting + ", " + this.name);
}

greet.call(person, "Hello"); // Hello, Ada

Arguments are passed one by one.

apply()

Same as call, but arguments go in an array:

greet.apply(person, ["Hello"]); // Hello, Ada

bind()

bind does NOT run the function. It returns a new function with this fixed:

const greetAda = greet.bind(person);
greetAda("Hi"); // Hi, Ada

call vs apply vs bind

  • call: runs now, arguments listed.
  • apply: runs now, arguments in an array.
  • bind: returns a bound function to call later.

TL;DR

  • call runs with given this and listed args.
  • apply runs with given this and array args.
  • bind creates a new function with fixed this.