Preview:
The call() Method

/*The call() method invokes a function and explicitly defines its context. In other words, we can use call() to call a function and specify which object will be assigned to this. 
Consider the following example:*/

const user = {
  username: 'Peter',
  auth() {
    console.log(`${this.username} has logged in`);
  }
};

const adminAuth = user.auth;

adminAuth.call(user); // Peter has logged in 

/*We have already encountered some code very similar to the above example. Remember, if we were to call adminAuth() without using call() here, our context would be the global window object, and undefined would be returned. With call(), we can explicitly specify the context.

Let's discuss the possible parameters of the call() method:

-The first parameter is the context, i.e. the object to be written to this. In the above example, this is the user object.

-The following parameters (there can be as many as needed) are the actual parameters of the function that we're calling.

In the above example, we simply used call() to define our function's context. This time, we'll also pass an argument so we can welcome our user with a custom greeting message:*/

const user = {
  username: 'Peter',
  auth(greeting) { // now this function has the greeting parameter
    console.log(`${greeting} ${this.username}`);
  }
};

const adminAuth = user.auth;

adminAuth.call(user, 'Hello'); // Hello Peter 

/*Again, there's no limit to the number of arguments we can pass:*/

const user = {
  username: 'Peter',
  auth() {
    console.log(arguments); // outputting the arguments to the console
  }
};

const adminAuth = user.auth;

adminAuth.call(user, 1, 2, 3, 4, 5); // Arguments(5) { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5 } 
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter