Call, Apply & Bind Methods — Javascript

Manoj - Nov 1 - - Dev Community

Each and every function in JS has access to this keyword.

1. Call

It’s similar to function borrowing, where we can use functions / borrow functions from one object and use them with another object instead of redeclaring them.

let name = {
  firstnName: 'Manoj',
  secondName: 'Ravi',
  fullName: function (district, state) {
    return `${this.firstName} ${this.secondName} from ${district}, ${state}.`;
  }
};

let getFullDetails = function(district, state) {
  return `${this.firstName} ${this.secondName} from ${district}, ${state}.`;
};

name.fullName('Chennai', 'TN');  // Manoj Ravi from Chennai, TN.
getFullDetails.call(name, 'Chennai', 'TN');  // Manoj Ravi from Chennai, TN.

let name2 = {
  firstnName: 'Sanjay',
  secondName: 'Ravi',
};

name.fullName.call(name2, 'Coimbatore', 'TN');  // Sanjay Ravi from Coimbatore, TN.
getFullDetails.call(name2, 'Coimbatore', 'TN');  // Sanjay Ravi from Coimbatore, TN.
Enter fullscreen mode Exit fullscreen mode

Additional parameters can be shared in a comma-separated format.

2. Apply

Similar to call, the only difference is the way we pass arguments. Instead of passing them individually (in a comma-separated format), we pass them as an array.

let getFullDetails = function(district, state) {
  return `${this.firstName} ${this.secondName} from ${district}, ${state}.`;
};

let name = {
  firstnName: 'Manoj',
  secondName: 'Ravi'
};
getFullDetails.call(name, ['Chennai', 'TN']);  // Manoj Ravi from Chennai, TN.

let name2 = {
  firstnName: 'Sanjay',
  secondName: 'Ravi'
};
getFullDetails.call(name2, ['Coimbatore', 'TN']);  // Sanjay Ravi from Coimbatore, TN.

Enter fullscreen mode Exit fullscreen mode

3. Bind

Similar to call, this method does not invoke the function immediately; instead, it binds the function's reference and returns a new function that can be called later.

let getFullDetails = function(district, state) {
  return `${this.firstName} ${this.secondName} from ${district}, ${state}.`;
};

let name = {
  firstnName: 'Manoj',
  secondName: 'Ravi'
};


let printDetails = getFullDetails(name, 'Chennai', 'TN');
printDetails();  // Manoj Ravi from Chennai, TN.
Enter fullscreen mode Exit fullscreen mode

Thank you for reading! I hope you found this blog informative and engaging. If you notice any inaccuracies or have any feedback, please don’t hesitate to let me know.

. . .
Terabox Video Player