call, apply and bind sometimes we called it function borrowing
Call: it can map a function with different object like-
let name = {
firstName: 'Danish',
lastName: 'Raza',
};
let printFullName = function () {
console.log(this.firstName + ' ' + this.lastName);
};
let name2 = {
firstName: 'Lav',
lastName: 'Singhania',
};
console.log(printFullName.call(name2));
above code we can just call the function printFullName by passing the object which we want to call.
call method accept the object as a parameter which you want to call. In above case we are calling name 2 object
We can also pass the extra parameter to the call function like-
let name = {
firstName: 'Danish',
lastName: 'Raza',
};
let printFullName = function (hometown, state) {
console.log(
this.firstName + ' ' + this.lastName + ' is from ' + hometown + ', ' + state
);
};
let name2 = {
firstName: 'Lav',
lastName: 'Singhania',
};
console.log(printFullName.call(name2, 'uttam nagar east', 'delhi'));
in the same example we add the two extra parameter named hometown and state. by this way we can pass infinite no of parameters to the function.
apply: bind method is same as call method except we pass extra parameters in the array form, like-
let name = {
firstName: 'Danish',
lastName: 'Raza',
};
let printFullName = function (hometown, state) {
console.log(
this.firstName + ' ' + this.lastName + ' is from ' + hometown + ', ' + state
);
};
let name2 = {
firstName: 'Lav',
lastName: 'Singhania',
};
console.log(printFullName.apply(name2, ['uttam nagar east', 'delhi']));
bind: bind is bit different from these two. In bind method it returns the copy of the existing function that we can invoke later.
let name = {
firstName: 'Danish',
lastName: 'Raza',
};
let printFullName = function (hometown, state) {
console.log(
this.firstName + ' ' + this.lastName + ' is from ' + hometown + ', ' + state
);
};
let name2 = {
firstName: 'Lav',
lastName: 'Singhania',
};
const printName = printFullName.bind(name2, ['uttam nagar east', 'delhi'])
// printname is the copy of printFullName function which we are invoking below.
printName();
in this code snippet printName is the exact copy of prinFullName functon.
Top comments (0)