Programming Tutorials

call in JavaScript

By: Yolander in Javascript Tutorials on 2023-04-26  

In JavaScript, call() is a method that allows you to call a function with a given this value and arguments provided individually. The syntax for call() is:

function.call(thisArg, arg1, arg2, ...)

Here, thisArg is the value of this that you want to set for the function being called, and arg1, arg2, etc. are the arguments that you want to pass to the function.

The call() method is similar to the apply() method, but with call() the arguments are provided individually rather than as an array.

Here is an example:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  fullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
};

const greeting = function() {
  return 'Hello, ' + this.fullName();
}

const message = greeting.call(person);
console.log(message); // "Hello, John Doe"

In the above example, the call() method is used to invoke the greeting function with person as the this value. Inside the greeting function, the this.fullName() expression is evaluated with this referring to person, and the resulting string is returned. Finally, the resulting message is logged to the console.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)