Skip to main content

The Magic of this, call(), apply(), and bind() in JavaScript

Control what 'this' points to - and unlock method borrowing

Updated 13 min readMarkdown
The Magic of this, call(), apply(), and bind() in JavaScript

What is 'this' in JavaScript?

this is a special keyword in JavaScript that refers to the object that is currently calling the function. It's like a pronoun it means 'me' or 'the current owner'.

The simplest way to think about it:
'this' always refers to whoever is calling the function at that moment.

Here is the most important thing to learn: this is not fixed - it changes depending on how the function is called. The same function can have a different this value in different situations.

// 'this' depends on WHO calls the function

function showName() {
    console.log(this.name);
}

const alice = { name: 'Alice', showName };
const bob   = { name: 'Bob',   showName };


alice.showName();   // Alice  - 'this' is alice
bob.showName();     // Bob    - 'this' is bob
// Same function, different 'this' each time!

'this' in Different Contexts'

this behaves differently depending on where and how the function is used. Here is an overview:

Global Object Method Arrow Function call/bind/apply
this obj.method() () => this fn.call(x)
window / global obj inherited outer x ( which we choose)

this in global scope

//In a Browser 'this' in global scope = window
function test(){
    console.log(this);    // window (in browser)
}
test();

//In strict mode, 'this' is undefined
'use strict';
function strictTest(){
    console.log(this);    //undefined
}

strictTest();

this inside an object method

When a function is called as a method of an object, this points to that object:

const person = {
    name: 'Rushi',
    age: 22,
    greet() {
        // 'this' = person (the object before the dot)
        return 'Hi! I am' + this.name + ', aged' + this.age;
    }
};

console.log(person.greet());    // Hi! I am Rushi, aged 22

this inside arrow functions

Arrow functions do NOT have their own this. They inherit it from the surrounding context where they were defined:

const person = {
    name: 'Rushi',
    greetNormal: function() {
        return 'Normal: ' + this.name;    // 'this' = person
    };
    greetArrow: () => {
        return 'Arrow: ' + this.name;    // 'this' = outer (window!)
    }
};

console.log(person.greetNormal());    //Normal: Rushi
console.log(person.greetArrow());    //Arrow: undefined.

Arrow functions and 'this'

Never use arrow functions as object methods if we need to access 'this' inside them. Arrow functions don't have their own 'this' - they look outside to find it, which is usually not what we want in an object.

'this' caller relationship

call() - Borrow a method immediately

Story:
When for a particular event we hire a chef, they come directly to our home to prepare food, but there are some big caterers they don't come personally they send their team for cooking.
This is what bind call and apply does.

call and apply => basic chef (need to provide kitchen)(cooks immediately)
bind => bind bolta hai mai kisiko bhejunga team will come means vo ek naya function return karega.

call() is a method that every function has. It lets you call a function and manually tell it what this should be. You pass argument one by one.

function cookDish(ingredient, style) {
    return `\({this.name} prepares \){ingredient} in ${style} style`
}
console.log(cookDish());
//Output -> undefine prepares undefine in undefine style

const sharmaKitchen = { name: "Sharma jis kitchen" };
const guptaKitchen = { name: "gupta jis kitchen" };

console.log(cookDish(sharmaKitchen, "Paneer & Spices", "Muglai"));
             // 1                    2                  3 
//Output -> undefine prepares [object object] in panner & Spices style

//But cookDish can take 2 arguments since 2 parameter
//hence, we use call method


                    //argument ki list pass krdo
console.log(cookDish.call(sharmakitchen, "Panner & Spices", "Muglai"));
//Output -> Sharma jis kitchen prepares Paneer & Spices in Muglai Style

Basic call() example

function greet(greeting) {
    return greeting + ', I am ' + this.name + '!';
}

const alice = { name: 'Alice' };
const bob = { name: 'Bob' };

//Call greet(), but set 'this' to alice
console.log(greet.call(alice, 'Hello'));    //Hello, I am Alice

Method borrowing with call()

The most practical use of call() is method borrowing - using a method from one object on a completely different object that doesn't have it:

const alice = {
    name: 'Alice',
    age: 22,
    greet(){
        return 'Hi, I am ' + this.name + ', aged' + this.age;
    }
}

const bob = {
    name: 'Bob',
    age: 30
    //bob has NO greet() method!
};

//Bob 'borrows' alice's greet method
console.log(alice.greet.call(bob));    // Hi, I am Bob, aged 30

// 'this' inside greet() is now 'bob' - not 'alice'

call() with multiple arguments

function introduce(city, job) {
    return this.name + 'from ' + city + ', works as ' + job;
}

const riya = { name: 'Riya' };
const arjun = { name: 'Arjun' };

//args passed one by one after the 'this' value
console.log(introduce.call(riya, 'Mumbai', 'Developer'));
//Riya from Mumbai, works as Developer

console.log(introduce.call(arjun, 'Delhi', 'Designer'));
//Arjun from Delhi, works as Designer

When we know that call and apply both are basic then What is the difference?
The call() method is a powerful, predefined method used to invoke a function with a specified 'this' value.
this allows an object to use a method that to another object.

apply() - Same as call(), but args in Array

apply() works exactly like call() - it calls the function with a custom this immediately. the only difference is how we pass the argument: apply() takes them as a single array instead of listing them one by one.

call() vs apply()

call() = C = Comma separated args. | apply() = A = Array of args

function cookDish(ingredient, style) {
//                1                     2              3
    return `\({this.name} prepares \){ingredient} in ${style} style`
}

const sharmaKitchen = { name: "Sharma jis kitchen" };
const guptaKitchen = { name: "gupta jis kitchen" };

const guptaOrder = ["Chole Kulche", "Punjabi Dishes"] 

console.log(cookDish(guptaKitchen, guptaOrder));

//              1                    2                        3
//Output -> undefined prepares [object object] in Chole Kulche, Punjabi Dishes style

In the above example guptaOrder is accessed in '\('{style} while guptaKitchen is accessed in '\)'{ingredients}, so we get to know it goes order wise how the arguments are passed that is accessed first.

Now we know that guptaOrder is an array & we need to pass those array elements as argument hence we use apply

console.log(cookDish.apply(guptaKitchen, guptaOrder));
//Output -> Gupta jis kitchen prepares Chole Kulche in Punjabi Style

What if we use call() here?

console.log(cookDish.call(guptaKitchen, guptaOrder));
//Output -> Gupta jis kitchen prepares Chole Kulche, Punjabi Dishes in undefined style.

The apply() method allows us to call a function with a specified 'this' value & argument provided as an array or an array like object.

Basic apply() example

function introduce(city, job) {
  return this.name + ' from ' + city + ', works as ' + job;
}


const riya = { name: 'Riya' };


// call() - args listed separately
introduce.call(riya, 'Mumbai', 'Developer');


// apply() - args in ONE array
const args = ['Mumbai', 'Developer'];
introduce.apply(riya, args);


// Both produce identical output:
// Riya from Mumbai, works as Developer

call() vs apply()

Practical apply() use - Math.max with an array

apply() is especially useful when the arguments are already stored in an array. A classic example is using Math.max() with the list of numbers:

const numbers = [3, 17, 5, 42, 8, 29];

// Problem: Math.mac() expects individual args, not an array
// Math.max(numbers -- WRONG, returns NaN

// Solution 1: apply() (classic way)
const max1 = Math.max.apply(null, numbers);
console.log(max1); //42

// Solution 2: spread operator
const max2 = Math.max(...numbers);
console.log(max2);

// apply() is great when we have arrays of arguments

Why null in Math.max.apply(null, ...) ?

Math.max() doesn't use 'this' internally, so we pass null as the first argument (the 'this' value). When a function does not need 'this', passing null is the standard convention.

bind() - Lock 'this' and Save for Later

bind() is different from call() and apply(). Instead of calling the function immediately, it returns a brand new function with this permanently locked to the value we specify. We can then call that new function whenever we need it.

Bind returns a new function that what's important here, whole apply & call returns result.

function reportDelivery(location, status) {
    return `\({this.name}  at \){location}: ${status}`
}

const deliveryBoy = { name: "Ranveer" };
//Now we share the name reference as this in other function with the help of call, bind and apply.

console.log("Call:", reportdelivery.call(deliveryBoy, "Lyari", "Ordered"));
//Output -> Call: Ranveer at Lyari : Ordered.

console.log("Apply:", reportdelivery.apply(deliveryBoy, "Mars", "Pickup"));
//Output -> Apply: Ranveer at Mars : Pickup.

console.log("Bind:", reportdelivery.bind(deliveryBoy, "Haridwar", "Delivered"));
//Output -> Bind: [Function: bound reportDelivery]

// we can see that we are getting a function reference in written

As we can see that while executing bind we are getting a function reference, so this tells us that bind returns a function instead of printing result.

To execute bind successfully, we need to store the reportDelivery.bind in a variable and then it returns a function so we need to execute the variable.

const bindReport = reportDelivery.bind(deliveryBoy, "Haridwar", "Delivered");
console.log(bindReport());
//Output -> Ranveer at Hardiwar : Delivered

Now there are ways to pass the variables deliveryBoy is to for sure passing, what we can do is pass "Haridwar" Now and later "Delivered" when we call the bindReport function or pass both later on also works.

const bindReport1 - reportDelivery.bind(deliveryBoy);
console.log(bindReport1("Haridwar", "Delivered"));
//Output -> Ranveer at Haridwar Delivered

What if we pass all 3 later on?
No agar sab badme pass krenge to bind ko reference kaha se milega.

Basic bind() example

function greet(greeting) {
  return greeting + ', I am ' + this.name;
}


const alice = { name: 'Alice' };


// bind() returns a NEW function - does NOT call it yet
const greetAlice = greet.bind(alice);


// Now call it whenever you need it
console.log(greetAlice('Hello'));  // Hello, I am Alice
console.log(greetAlice('Hi'));     // Hi, I am Alice
console.log(greetAlice('Hey'));    // Hey, I am Alice


// 'this' is ALWAYS alice - no matter how you call greetAlice

bind() with pre-set arguments

function multiply(x, y) {
  return x * y;
}


// Create a 'double' function by locking x = 2
const double = multiply.bind(null, 2);
console.log(double(5));    // 10  (2 * 5)
console.log(double(8));    // 16  (2 * 8)


// Create a 'triple' function by locking x = 3
const triple = multiply.bind(null, 3);
console.log(triple(5));    // 15  (3 * 5)
console.log(triple(8));    // 24  (3 * 8)

Real use case - bind() in event handlers

bind() is most commonly used when passing methods as callbacks (like event handlers), where this can get lost if not bound:

class Counter {
    constructor() {
        this.count = 0;
    }

    increment() {
        this.count++; 
        console.log('Count: ' + this.count);
    }
}

const counter = new Counter(); // Also known as detached method

// Problem: passing method as callback looses 'this'
// setTimeout(counter.increment, 1000);  // NaN - 'this' is lost;

// Solution: bind() fixes 'this' permanently 
setTimeout(counter.increament.bind(counter), 1000);
// Count: 1 - works correctly!

bind() - the "save for later" method

Think of bind() as putting a name tag on a function. The tag says 'when you run me. my this is ALWAYS this specific object'. No matter where the function ends up - in a setTimeout, an event Listener, or passes as a callback - it always knows who it belongs to.

call() vs apply() vs bind()

To decide which one to use, ask yourself:

  • Do I want to call it right now with args listed one by one? Use call()

  • Do I want to call it right now with args in an array? Use apply()

  • Do I want to save it for later with this locked? Use bind()

All 3 Together

function introduce(city, language) {
  return this.name + ' from ' + city + ', speaks ' + language;
}


const dev = { name: 'Priya' };


// ── call() - run immediately, args one by one
const result1 = introduce.call(dev, 'Pune', 'JavaScript');
console.log(result1);
// Priya from Pune, speaks JavaScript


// ── apply() - run immediately, args as array
const args = ['Pune', 'JavaScript'];
const result2 = introduce.apply(dev, args);
console.log(result2);
// Priya from Pune, speaks JavaScript


// ── bind() - save a new function for later
const introducePriya = introduce.bind(dev);
console.log(introducePriya('Pune', 'JavaScript'));
// Priya from Pune, speaks JavaScript


// bind() creates a reusable function!
console.log(introducePriya('Mumbai', 'Python'));
// Priya from Mumbai, speaks Python

Practice Assignment

Task 1 - Create an object with a method using this

const student = {
  name: 'Rushi',
  marks: 88,
  describe() {
    return this.name + ' scored ' + this.marks + ' marks';
  }
};

console.log(student.describe());
// Rushi scored 88 marks

Task 2 - Borrow that method using call()

// Another student without a describe() method
const student2 = { name: 'Suraj', marks: 92 };

// Borrow describe from student using call()
console.log(student.describe.call(student2));
// Suraj scored 92 marks

// Create a standalone function and call() it with student
function fullReport(subject, grade) {
  return this.name + ': ' + subject + ' - Grade ' + grade;
}
console.log(fullReport.call(student, 'Maths', 'A'));
// Rushi: Maths - Grade A

Task 3 - Use apply() with array arguments

function summary(subject, grade, year) {
  return this.name + ' | ' + subject + ' | ' + grade + ' | ' + year;
}

const args = ['Physics', 'B+', 2024];

console.log(summary.apply(student, args));
// Rushi | Physics | B+ | 2024

// Apply with Math.max on an array
const allMarks = [78, 88, 92, 65, 95];
console.log(Math.max.apply(null, allMarks));   // 95

Task 4 - Use bind() and store the function

// Bind fullreport to stundet and save it
const rushiReport = fullReport.bind(student);

// Call the bound function later with different args
console.log(rushiReport("Maths", "A")) // Rushi: Maths - Grade A
console.log(rushiReport("Science", "B"))  // Rushi: Science - Grade B
console.log(rushiReport("English", "A+"))  // Rushi: English - Grade A+

// 'this' is ALWAYS student no matter what args we pass

Conclusion

Here is everything you learned in this article:

  • this always refers to whoever is calling the function - it changes based on how the function is called

  • In global scope: this is window (browser) or global (Node)

  • In an object method: this is the object before the dot - e.g., alice.greet() means this = alice

  • In arrow functions: this is inherited from the outer scope - not the calling object

  • call(thisVal, arg1, arg2) - calls immediately, args listed one by one

  • apply(thisVal, [arg1, arg2]) - calls immediately, args as an array

  • bind(thisVal) - returns a new function with this locked, for calling later

  • Method borrowing - use call() or apply() to use one object's method on a different object

  • Partial application - use bind() to pre-set arguments and create specialised functions

Mastering this, call(), apply(), and bind() unlocks a much deeper understanding of how JavaScript functions work. These concepts come up constantly in class methods, event handlers, React components, and any code involving callbacks.

About the author

  • the topics and concepts which i learn and get more fascinated i write about them here...

No comments yet. Be the first to comment.