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 becomesthisinside 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 AliceHere 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 developerExample 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 AliceExample 4 - calling built-in functions on foreign objects
javascript
const arr = ['a', 'b', 'c'];
console.log(Array.prototype.join.call(arr, '-')); // a-b-cHere 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
| Method | What it does | How arguments are passed |
|---|---|---|
| call | calls a function with a given this | comma-separated |
| apply | calls a function with a given this | as an array |
| bind | returns 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
nullorundefinedasthisArg, then inside the function:- in strict mode (
'use strict')thisisundefined; - in non-strict mode
thisbecomes the global object (windowin the browser).
- in strict mode (
javascript
function showThis() {
console.log(this);
}
showThis.call(null); // window (in non-strict mode)Summary
| What it does | Controls the value of this when calling a function |
|---|---|
| Calls the function immediately | Yes |
| Returns a new function | No |
| How arguments are passed | Comma-separated |
| Supports closures | Yes |
| Safety | Safe, as long as you don't pass null without 'use strict' |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.