Call
function greet(name,age){
return `my name is ${name} and age ${age}`
}
let result = greet("pankaj",100);
console.log(result);
Here, you're simply calling the greet() function with arguments directly. This works fine, and there's no need for call() in this case because you're just invoking the function as usual.
Use Call
function greet(name,age){
console.log(`my name is ${name} and age ${age}`)
}
let result = greet("pankaj",100);
let result2 = greet("raju",200);
console.log(result);
console.log(result2);
function greet1(name,age){
console.log(`my name is ${this.name} and age ${this.age}`)
}
let person1 = {
name:"Raju",
age:11,
}
let person2 = {
name:"pankaj",
age:10
}
console.log("CALL............")
greet1.call(person1)
greet1.call(person2)
function greet(name, age) {
console.log(`my name is ${name} and age ${age}`);
}
Name and Age pass directly but not in call
function greet1() {
console.log(`my name is ${this.name} and age ${this.age}`);
}
Pass explicit
function showDetails() {
console.log(`Hi, I'm ${this.name} and I live in ${this.city}`);
}
const user1 = { name: "Anita", city: "Delhi" };
const user2 = { name: "Karan", city: "Mumbai" };
showDetails.call(user1);
showDetails.call(user2);
Imagine a utility function that logs details. Instead of rewriting it inside every object, you define it once and use .call():
Apply: It's simmilar to call but main difference we have pass list of arguments.
function showDetails(cource,country) {
console.log(`Hi, I'm ${this.name} and I live in ${this.city} and courece ${cource}- ${country}`);
}
const user1 = { name: "Anita", city: "Delhi" };
const user2 = { name: "Karan", city: "Mumbai" };
// showDetails.call(user1, "rajpur");
// showDetails.call(user2, "Dehradun");
showDetails.apply(user1, ["rajpur","India"]);
showDetails.apply(user2, ["Dehradun","India"]);
Use Case 1: Save a Function with Fixed this for Later Use
const person = {
name: "Pankaj",
greet: function () {
console.log(`Hello, I am ${this.name}`);
}
};
const greetFunc = person.greet.bind(person); // Fixes `this` to `person`
setTimeout(greetFunc, 1000); // Will print: Hello, I am Pankaj
Use Case 2: Reuse a Function with a Specific Context
function showDetails(course) {
console.log(`${this.name} from ${this.city} is enrolled in ${course}`);
}
const user1 = { name: "Ravi", city: "Delhi" };
const showForUser1 = showDetails.bind(user1);
showForUser1("JavaScript");
Use Case 3: Partial Function Application (Pre-set Arguments)
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2); // Fix `a` as 2
console.log(double(5)); // 10
Comments
Post a Comment