Day 10: JavaScript Call, Apply & Bindβ€Š-β€ŠMastering Function Borrowing πŸš€

Introduction ✨

In JavaScript, functions are first-class citizens, meaning they can be passed as arguments, returned from other functions, and even borrowed by different objects. This is where call(), apply(), and bind() methods come into play. These methods allow us to borrow functions from one object and use them with another object. πŸ”₯

In this post, we’ll understand these methods with real-world use cases and examples. πŸ†


1️⃣ Understanding call(), apply(), and bind() πŸ€”

These three methods are used to manipulate the this keyword inside a function.

1.1) call() Method πŸ“ž

The call() method invokes a function and allows you to pass arguments one by one.

Syntax:

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

Example:

const person1 = {
    name: "Lokesh",
    greet: function(age) {
        console.log(`Hello, my name is ${this.name} and I am ${age} years old.`);
    }
};

const person2 = { name: "Mukesh" };
person1.greet.call(person2, 25);
// Output: Hello, my name is Mukesh and I am 25 years old.

πŸ“Œ Here, call() changes the this context from person1 to person2. βœ…


1.2) apply() Method 🎯

The apply() method is similar to call(), but instead of passing arguments individually, you pass them as an array.

Syntax:

functionName.apply(thisArg, [arg1, arg2, ...]);

Example:

const numbers = {
    max: function(a, b, c) {
        return Math.max(a, b, c);
    }
};

console.log(numbers.max.apply(null, [10, 20, 30]));
// Output: 30

πŸ“Œ Best used when arguments are already in an array format. πŸ’‘


1.3) bind() Method πŸ”—

The bind() method does not invoke the function immediately. Instead, it returns a new function with the specified this value.

Syntax:

const newFunction = functionName.bind(thisArg, arg1, arg2, ...);

Example:

const user = {
    name: "Lokesh",
    greet: function() {
        console.log(`Hello, I am ${this.name}`);
    }
};


const greetUser = user.greet.bind(user);
greetUser();
// Output: Hello, I am Lokesh

πŸ“Œ Best used when you need to maintain the this context for later execution. ⚑


Real-World Use Cases 🌍

1️⃣ Borrowing Methods πŸ”„

const car = { brand: "Toyota" };
const bike = { brand: "Yamaha" };

function showBrand() {
    console.log(this.brand);
}
showBrand.call(car);  // Output: Toyota
showBrand.call(bike); // Output: Yamaha

2️⃣ Finding Maximum in an Array πŸ”’

const numbers = [12, 45, 78, 34];
console.log(Math.max.apply(null, numbers)); // Output: 78

3️⃣ Setting this in Event Listeners πŸ–±οΈ

class Button {
    constructor(label) {
        this.label = label;
    }

    handleClick() {
        console.log(`Button ${this.label} clicked`);
    }
}

const btn = new Button("Submit");
document.querySelector("button").addEventListener("click", btn.handleClick.bind(btn));

πŸ“Œ Using bind() ensures this refers to the correct object inside event listeners. 🎯


Conclusion 🏁

  • call() – Calls the function immediately, passing arguments one by one.

  • apply() – Calls the function immediately, passing arguments as an array.

  • bind() – Returns a new function, preserving the this context.

Understanding these methods will make you a better JavaScript developer, especially when working with function borrowing, event listeners, and array manipulations. πŸš€

0
Subscribe to my newsletter

Read articles from Lokesh Prajapati directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lokesh Prajapati
Lokesh Prajapati

πŸš€ JavaScript | React | Shopify Developer | Tech Blogger Hi, I’m Lokesh Prajapati, a passionate web developer and content creator. I love simplifying JavaScript, React, and Shopify development through easy-to-understand tutorials and real-world examples. I’m currently running a JavaScript Basics to Advanced series on Medium & Hashnode, helping developers of all levels enhance their coding skills. My goal is to make programming more accessible and practical for everyone. Follow me for daily coding tips, tricks, and insights! Let’s learn and grow together. πŸ’‘πŸš€ #JavaScript #React #Shopify #WebDevelopment #Coding #TechBlogger #LearnToCode