JavaScript - call, apply, bind

Overview

Estimated time: 20–30 minutes

Set the this context and pass arguments explicitly using call, apply, and bind.

Learning Objectives

  • Use call and apply to invoke functions with a specific this.
  • Use bind to create a new function with preset this and/or arguments.

Prerequisites

Examples

function greet(greeting) {
  return `${greeting}, ${this.name}`;
}
const user = { name: 'Ada' };

greet.call(user, 'Hello');      // 'Hello, Ada'
greet.apply(user, ['Hi']);      // 'Hi, Ada'
const hi = greet.bind(user, 'Hi');
hi();                            // 'Hi, Ada'

Common Pitfalls

  • Arrow functions ignore call/apply this because their this is lexical.
  • bind returns a new function; remember to call it.