Home >Web Front-end >JS Tutorial >Call, Apply & Bind Methods — Javascript

Call, Apply & Bind Methods — Javascript

Susan Sarandon
Susan SarandonOriginal
2024-11-03 01:09:291008browse

Call, Apply & Bind Methods — Javascript

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.

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.

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.

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.

The above is the detailed content of Call, Apply & Bind Methods — Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn