JavaScript Function Call

Using the call() method to control function execution

📞 What is Function call()?

The call() method allows you to call a function with a specific 'this' value and arguments. It lets you borrow methods from other objects.


function greet() {
    return "Hello, " + this.name;
}

let person = { name: "Alice" };

// Use call() to set 'this' to person
let message = greet.call(person);
console.log(message);
                                    

Output:

"Hello, Alice"

call() Method Features

🎯

Set 'this'

Control what 'this' refers to

func.call(thisArg)
📝

Pass Arguments

Send arguments individually

func.call(this, arg1, arg2)
🔄

Borrow Methods

Use methods from other objects

obj1.method.call(obj2)

Immediate Execution

Function runs immediately

// Executes right away

🔹 Basic call() Usage

Using call() to set the 'this' context:

function introduce() {
    return "Hi, I'm " + this.name + " and I'm " + this.age + " years old";
}

let person1 = { name: "Alice", age: 25 };
let person2 = { name: "Bob", age: 30 };

// Use the same function with different objects
console.log(introduce.call(person1));
console.log(introduce.call(person2));

Output:

Hi, I'm Alice and I'm 25 years old
Hi, I'm Bob and I'm 30 years old

🔹 call() with Arguments

Passing arguments along with the 'this' context:

function greetWithTitle(title, greeting) {
    return greeting + " " + title + " " + this.name + "!";
}

let person = { name: "Smith" };

// Pass 'this' context and arguments
let formal = greetWithTitle.call(person, "Dr.", "Good morning");
let casual = greetWithTitle.call(person, "Mr.", "Hey");

console.log(formal);
console.log(casual);

Output:

Good morning Dr. Smith!
Hey Mr. Smith!

🔹 Borrowing Methods with call()

Use methods from one object on another object:

let car = {
    brand: "Toyota",
    start: function() {
        return this.brand + " is starting...";
    },
    stop: function() {
        return this.brand + " has stopped.";
    }
};

let motorcycle = { brand: "Honda" };

// Borrow car methods for motorcycle
console.log(car.start.call(motorcycle));
console.log(car.stop.call(motorcycle));

Output:

Honda is starting...
Honda has stopped.

🔹 call() vs Normal Function Call

Comparing regular function calls with call() method:

let calculator = {
    value: 0,
    add: function(num) {
        this.value += num;
        return this.value;
    }
};

let counter = { value: 10 };

// Normal method call
console.log("Calculator:", calculator.add(5)); // Uses calculator.value

// Using call() to use calculator's method on counter
console.log("Counter:", calculator.add.call(counter, 5)); // Uses counter.value

// Check the values
console.log("Calculator value:", calculator.value);
console.log("Counter value:", counter.value);

Output:

Calculator: 5
Counter: 15
Calculator value: 5
Counter value: 15

🔹 Practical call() Example

Using call() to convert array-like objects:

// Array-like object (like arguments or NodeList)
function showArguments() {
    // arguments is array-like but not a real array
    console.log("Arguments object:", arguments);
    
    // Borrow Array's slice method to convert to real array
    let realArray = Array.prototype.slice.call(arguments);
    console.log("Real array:", realArray);
    
    // Now we can use array methods
    console.log("Joined:", realArray.join(" - "));
}

showArguments("apple", "banana", "cherry");

Output:

Arguments object: {"0": "apple", "1": "banana", "2": "cherry"}
Real array: ["apple", "banana", "cherry"]
Joined: apple - banana - cherry

🧠 Test Your Knowledge

What does the call() method do?