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());