Skip to main content

Function.prototype.call

What call does

call() runs a function, specifying exactly which object will be this inside it, and passes arguments comma-separated.

Syntax:

javascript
func.call(thisArg, arg1, arg2, ...)
  • func - the function itself that you are calling;
  • thisArg - the object that becomes this inside the function;
  • arg1, arg2, ... - the arguments passed to the function.

Example 1 - simple case

javascript
function greet() { console.log(`Hi, I'm ${this.name}`); } const user = { name: 'Alice' }; greet.call(user); // Hi, I'm Alice

Here this inside greet now points to the user object.


Example 2 - with arguments

javascript
function introduce(city, job) { console.log(`I'm ${this.name} from ${city}, I work as a ${job}`); } const person = { name: 'Alice' }; introduce.call(person, 'Kyiv', 'Frontend developer'); // I'm Alice from Kyiv, I work as a Frontend developer

Example 3 - borrowing a method

Sometimes it's convenient to temporarily "borrow" a method from one object for another:

javascript
const user1 = { name: 'Maria', sayHi() { console.log(`Hi, I'm ${this.name}`); } }; const user2 = { name: 'Alice' }; user1.sayHi.call(user2); // Hi, I'm Alice

Example 4 - calling built-in functions on foreign objects

javascript
const arr = ['a', 'b', 'c']; console.log(Array.prototype.join.call(arr, '-')); // a-b-c

Here we explicitly call the join method on the Array prototype, passing arr as the context. This is useful when an object is array-like (for example, arguments or NodeList).


Difference between call, apply, bind

MethodWhat it doesHow arguments are passed
callcalls a function with a given thiscomma-separated
applycalls a function with a given thisas an array
bindreturns a new function with this "bound"comma-separated

Comparison example:

javascript
function sum(a, b) { return a + b; } console.log(sum.call(null, 1, 2)); // 3 console.log(sum.apply(null, [1, 2])); // 3 const bound = sum.bind(null, 1, 2); console.log(bound()); // 3 (called later)

Features

  • If you pass null or undefined as thisArg, then inside the function:
    • in strict mode ('use strict') this is undefined;
    • in non-strict mode this becomes the global object (window in the browser).
javascript
function showThis() { console.log(this); } showThis.call(null); // window (in non-strict mode)

Summary

What it doesControls the value of this when calling a function
Calls the function immediatelyYes
Returns a new functionNo
How arguments are passedComma-separated
Supports closuresYes
SafetySafe, as long as you don't pass null without 'use strict'

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.