JavaScriptMedium
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) orObject.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 withthisfixed.
A memory trick: Apply takes an Array, Call takes Commas.
Details
- In strict mode
thisArgis used exactly as given, evennullor a primitive. In sloppy modenull/undefinedbecome the global object and primitives are boxed. - Arrow functions ignore the
thisArg. - With spread syntax,
fn.call(ctx, ...args)covers almost everythingapplyused 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";23function introduce(greeting, punctuation) {4 return `${greeting}, I'm ${this.name}${punctuation}`;5}67const ada = { name: "Ada" };8const grace = { name: "Grace" };910console.log(introduce.call(ada, "Hello", "!")); // Hello, I'm Ada!11console.log(introduce.call(grace, "Hi", ".")); // Hi, I'm Grace.1213// Borrowing a method for a precise type check14const typeOf = (v) => Object.prototype.toString.call(v).slice(8, -1);15console.log(typeOf([]), typeOf(null), typeOf(new Date()), typeOf(/x/)); // Array Null Date RegExp1617// Borrowing an array method for an array-like object18const arrayLike = { 0: "a", 1: "b", length: 2 };19console.log(Array.prototype.map.call(arrayLike, (s) => s.toUpperCase())); // ["A", "B"]2021// 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.