JavaScript(JS) function method - call

www.igift‮c.aedi‬om

The call() method is a built-in function in JavaScript that allows you to invoke a function with a specific this value and arguments provided individually. It can be used to change the context of a function, which refers to the object that the function belongs to.

The syntax for using the call() method is as follows:

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

Here, functionName is the function that you want to invoke, thisArg is the value of this that you want to set within the function, and arg1, arg2, etc. are the arguments that you want to pass to the function. If the function does not require any arguments, you can omit them.

Here's an example that demonstrates how to use the call() method:

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

person.greet(); // Output: "Hello, my name is John and I am 30 years old."

const anotherPerson = {
  name: "Alice",
  age: 25,
};

person.greet.call(anotherPerson); // Output: "Hello, my name is Alice and I am 25 years old."

In the example above, we have an object person with a greet() method that uses this to refer to the person object. We also have another object anotherPerson with a name and age property. By using the call() method on the greet() method of person, we can set this to anotherPerson, and as a result, the output will show the values of name and age of anotherPerson.