How to manually pass the value of ‘this’ object in a JavaScript function

Every JavaScript function has a ‘this’ object, and the value of ‘this’ object depends on the way you call the function. To pass the value of ‘this’ manually, you need to call the function indirectly.

In JavaScript, you call a function indirectly to pass the value of ‘this’ object manually.

Manually calling a function is also known as the Indirect Invocation Pattern.  JavaScript provides three methods to call a function indirectly.  They are,

  1. call method
  2. apply method
  3. bind method

Let us consider a function sendInvoice as below,


function sendInvoice(email = "hello@geek97.com") {
    this.email = email;
    console.log(this);
}

Next, you have two objects as below,


let Invoice1 = {
 
    InvId: '1',
    Title: 'Angular Training',
    Teacher: 'Dhananjay',
    Date: new Date()
}
 
let Invoice2 = {
    InvId: '2',
    Title: 'C# Training',
    Teacher: 'Shiv',
    Date: new Date()
}

Now you have a requirement to pass these two objects Invoice1 and Invoice2 inside the sendInvoice function as the ‘this’ object.  You can do that by using the call method as below,


sendInvoice.call(Invoice1, 'a@a.com');
sendInvoice.call(Invoice2, 'b@b.com');

You can also use the apply method as below,


sendInvoice.apply(Invoice1, ['a@a.com']);
sendInvoice.apply(Invoice2, ['b@b.com']);

In both call and apply methods,

  • The first argument is the object which you wish to pass as the ‘this’ object
  • In the apply method, the second argument is an array that contains all the arguments to the function
  • In the call method, second arguments onwards are the arguments to the function.

So, by indirectly calling a function using the call or apply method, you can manually pass the value of ‘this’ object.

I hope you find this post useful. Thanks for reading.


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading