JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Function call()

14 April 2025 | Category:

In JavaScript, the call() method is a built-in function method that allows you to call a function with a specific this value and pass arguments one by one.

It’s useful when you want to borrow a function from one object and use it in the context of another object.


🧠 Syntax

functionName.call(thisArg, arg1, arg2, ...);

Parameters:

  • thisArg: The value to use as this when the function is called.
  • arg1, arg2, ...: Arguments passed to the function.

✅ Basic Example

function greet(city) {
  console.log(`Hi, I'm ${this.name} from ${city}`);
}

const person = { name: "Alice" };

greet.call(person, "New York"); // Hi, I'm Alice from New York

🧩 greet isn’t a method of person, but using call() sets this to person.


🧲 Why Use call()?

  1. Function borrowing
  2. Controlling the context (this)
  3. Reusability across multiple objects

🔁 call() vs apply()

Featurecall()apply()
ArgumentsPassed individuallyPassed as an array
Examplefunc.call(obj, a, b)func.apply(obj, [a, b])
greet.call(person, "Delhi");
greet.apply(person, ["Delhi"]);

🧬 Function Borrowing Example

const user1 = {
  name: "John",
  greet: function () {
    console.log(`Hello, I'm ${this.name}`);
  }
};

const user2 = { name: "Emma" };

user1.greet.call(user2); // Hello, I'm Emma

📦 Using call() with Built-in Methods

const numbers = [5, 2, 8, 1];

const max = Math.max.call(null, ...numbers);
console.log(max); // 8

🔐 Real-world Use Case: Inheritance

function Animal(name) {
  this.name = name;
}

function Dog(name, breed) {
  Animal.call(this, name); // Call Animal with Dog's this
  this.breed = breed;
}

const myDog = new Dog("Buddy", "Labrador");
console.log(myDog); // { name: "Buddy", breed: "Labrador" }

⚠️ Notes

  • call() does not create a new function, it simply executes the existing function with a new context.
  • If null or undefined is passed as the thisArg, it defaults to the global object in non-strict mode or remains undefined in strict mode.

🧾 Summary

  • The call() method lets you invoke functions while explicitly setting the this context.
  • It’s extremely useful for function reuse, inheritance, and dynamic method calls.