JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Function Call


📘 JavaScript call() Method – Function Invocation with Custom Context

The call() method lets you invoke a function, explicitly setting the value of this and passing arguments one by one.


🔹 Syntax

func.call(thisArg, arg1, arg2, ...);
  • thisArg: Value to use as this inside the function.

  • arg1, arg2, ...: Arguments passed individually.


🔹 Example 1 – Basic Usage

function greet(city) {
  console.log(`Hello ${this.name} from ${city}`);
}

const person = { name: "Ravi" };

greet.call(person, "Delhi"); 
// Output: Hello Ravi from Delhi

🔹 Example 2 – Using Call to Borrow Methods

const person1 = {
  name: "Alice",
  greet: function () {
    console.log("Hi " + this.name);
  },
};

const person2 = { name: "Bob" };

person1.greet.call(person2); // Output: Hi Bob

🔹 call() vs apply()

Feature call() apply()
Syntax func.call(this, arg1, arg2) func.apply(this, [arg1, arg2])
Arguments Passed individually Passed as array

Practice Questions

Q1. Write a function sayName(greeting) that prints "greeting, my name is [this.name]". Use call() with { name: "Anjali" } and "Hello" as argument.

Q2. Create a function multiply(x, y) and call it using call() with null as this and numbers 4 and 5 as arguments.

Q3. Create two objects a and b. Let a have a method show() that prints this.value. Use call() to run a.show using b’s context.

Q4. Define a function introduce(city, country) and call it with call() using { name: "Meena" } and arguments "Mumbai", "India". Print a full sentence.

Q5. Create a function area(length, width) and invoke it with call() to calculate and log area of a rectangle.

Q6. Write a function describeRole() that logs this.name + " is a " + this.role. Use call() with two different objects.

Q7. Use a standalone function showBrand() and invoke it with call() using an object { brand: "Nike" } to print the brand.

Q8. Write a function sum(a, b, c) and use call() to pass the values 2, 3, 4 and log the result.

Q9. Create a method showDetails() in object user1 and use call() to reuse it for user2. Both objects should have name and age.

Q10. Create a function combine(first, second) and use call() with an object { separator: " & " } to print "first & second".


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top