difference between call apply bind in javascript

// call method calls a function with provided this reference and arguments
var person = {
  name: 'Default',
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + " lives in " + city + ", " + country
  }
};

person1 = {
  firstName: 'Jerry',
  lastName: 'Seinfeld',
};

person2 = {
  firstName: 'Michael',
  lastName: 'Scott'
};

/**
 * call and apply takes this reference of any object, with
 * a difference
 * [a]pply takes (a for array of arguments)
 * [c]all takes (c for comma separated arguments)
 * bind on the other hand also takes this reference of any object
 * but returns a new function that can be called.
 * bind also takes comma separated arguments or the arguments can
 * be passed to the returned function.
 * Examples:
 */
console.log("--apply--");
console.log(person.fullName.apply(person1, ["New York", "USA"]));
console.log(person.fullName.apply(person2, ["Scranton", "USA"]));
console.log("--call--");
console.log(person.fullName.call(person1, "New York", "USA"));
console.log(person.fullName.call(person2, "Scranton", "USA"));
console.log("--bind--");
var fullNameFunction1 = person.fullName.bind(person1);
var fullNameFunction2 = person.fullName.bind(person2);

console.log(fullNameFunction1);
console.log(fullNameFunction2);

console.log(fullNameFunction1 === fullNameFunction2);

console.log(fullNameFunction1("New York", "USA"));
console.log(fullNameFunction1("Scranton", "USA"));
console.log("--bind_no_args--");
var fullNameFunction1NoArgs = person.fullName.bind(person1, "New York", "USA");
var fullNameFunction2NoArgs = person.fullName.bind(person2, "Scranton", "USA");
console.log(fullNameFunction1NoArgs());
console.log(fullNameFunction2NoArgs());

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source