call, apply & bind

danishraza

Danish Raza

Posted on March 15, 2024

call, apply & bind

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));
Enter fullscreen mode Exit fullscreen mode

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'));
Enter fullscreen mode Exit fullscreen mode

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']));
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

in this code snippet printName is the exact copy of prinFullName functon.

💖 💪 🙅 🚩
danishraza
Danish Raza

Posted on March 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

call, apply & bind
javascript call, apply & bind

March 15, 2024