- The Call method is a predefined javaScript method.
- In JavaScript, the call method is used to invoke(call) a function with a specified this context and arguments provided individually.
Example 1 : (Using Call() method to invoke a function and specifying the this value )
function greeting() {
console.log(this.greet, "learnersstore.com");
}
const obj1 = {
greet: 'Hi'
}
const obj2 = {
greet: 'Hello'
}
greeting.call(obj1);
greeting.call(obj2);
Output :
Hi learnersstore.com
Hello learnersstore.com
Example 2 : (Using Call() method to invoke a function without first argument)
function greeting() {
console.log(this.greet, "learnersstore.com");
}
const obj1 = {
greet: 'Hi'
}
greeting.call();
Output :
undefined learnersstore.com
Note: If we are omitting the first parameter, then it returns undefined.
Example 3 : (Using Call() method to invoke a function without first argument But with globalThis)
globalThis.greet = "Hello";
function greeting() {
console.log(this.greet, "learnersstore.com");
}
const obj1 = {
greet: 'Hi'
}
greeting.call();
Output:
Hello learnersstore.com
Example 4 : (Using Call() method to invoke a function with multiple arguments)
function display(name, age) {
console.log(`Name : ${name}, Age: ${age}, Location: ${this.location}`);
}
const obj1 = {
location: 'India',
}
display.call(obj1, "Smith", 26);
Output :
Name : Smith, Age: 26, Location: India