Example 1: difference between call apply bind in javascript
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'
};
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());
Example 2: call() vs apply() vs bind()
Differentce between .bind() , .call() and .apply()
.bind(someobj) -> does not invoke the function, it just allows you to
bind whatever object you want, you have to call the function yourself.
.call(someobj) and .apply(someobj)-> both invoke the function
immediately,and modify the context.
The only difference is how you pass your
own arguments. See below
.call(someobj, param1, param2)
.apply(someobj, [param1, param2])
Example 3: javascript call() & apply() vs bind()?
Apply vs. Call vs. Bind Examples
Call
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.call(person1, 'Hello');
say.call(person2, 'Hello');
Apply
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.apply(person1, ['Hello']);
say.apply(person2, ['Hello']);
Bind
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say() {
console.log('Hello ' + this.firstName + ' ' + this.lastName);
}
var sayHelloJon = say.bind(person1);
var sayHelloKelly = say.bind(person2);
sayHelloJon();
sayHelloKelly();