Call Method Javascript
-
What is
call?call()is a method available on all functions- It allows you to invoke a function with a specified
thisvalue and individual arguments. call()takes an object as first argument, & then a list for the functions arguments on which it is called upon, refer example 2
-
Syntax:
functionName.call(thisArg, arg1, arg2, ...);functionName: The function you want to call.thisArg: The value to be used asthisinside the function.arg1, arg2, ...: The arguments to be passed to the function.
-
Example 1:
const person = { fullName: function() { return this.firstName + " " + this.lastName; } }; const person1 = { firstName: "John", lastName: "Doe", }; console.log( person.fullName.call(person1); ); // Outputs: "John Doe" -
Example 2:
var obj = { name: "Chaitanya" };
function sayHello(age) {
return "Hello " + this.name + " is " + age;
}
console.log(sayHello.call(obj, 22));