What is call()?

fn.call(thisArg, arg1, arg2, ...) calls a function immediately with this set to thisArg and the arguments passed one by one.

What it is used for

  • Borrowing methods: use a method from one object on another, e.g. Array.prototype.slice.call(arguments) (historically) or Object.prototype.toString.call(value) for precise type checks.
  • Calling a parent constructor in constructor-function inheritance: Parent.call(this, name).
  • Running a function with a specific context once, without permanently binding it.

call vs apply vs bind

  • call(this, a, b): run now, arguments listed individually.
  • apply(this, [a, b]): run now, arguments as an array.
  • bind(this, a, b): do not run; return a new function with this fixed.

A memory trick: Apply takes an Array, Call takes Commas.

Details

  • In strict mode thisArg is used exactly as given, even null or a primitive. In sloppy mode null/undefined become the global object and primitives are boxed.
  • Arrow functions ignore the thisArg.
  • With spread syntax, fn.call(ctx, ...args) covers almost everything apply used to be needed for.

Modern note

Many uses have cleaner alternatives: Array.from(arguments) or rest parameters instead of borrowing slice, and super(...) in classes instead of Parent.call(this).

Code example

js
1"use strict";
2
3function introduce(greeting, punctuation) {
4 return `${greeting}, I'm ${this.name}${punctuation}`;
5}
6
7const ada = { name: "Ada" };
8const grace = { name: "Grace" };
9
10console.log(introduce.call(ada, "Hello", "!")); // Hello, I'm Ada!
11console.log(introduce.call(grace, "Hi", ".")); // Hi, I'm Grace.
12
13// Borrowing a method for a precise type check
14const typeOf = (v) => Object.prototype.toString.call(v).slice(8, -1);
15console.log(typeOf([]), typeOf(null), typeOf(new Date()), typeOf(/x/)); // Array Null Date RegExp
16
17// Borrowing an array method for an array-like object
18const arrayLike = { 0: "a", 1: "b", length: 2 };
19console.log(Array.prototype.map.call(arrayLike, (s) => s.toUpperCase())); // ["A", "B"]
20
21// Calling a parent constructor (pre-class inheritance)
22function Person(name) {
23 this.name = name;
24}
25function Employee(name, role) {
26 Person.call(this, name); // run Person with the new Employee as `this`
27 this.role = role;
28}
29console.log(new Employee("Ada", "engineer")); // Employee { name: "Ada", role: "engineer" }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app