javascript call() & apply() vs bind()? code example
Example 1: 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]) //uses array to pass the args
Example 2: 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'); // Hello Jon Kuperman
say.call(person2, 'Hello'); // Hello Kelly King
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']); // Hello Jon Kuperman
say.apply(person2, ['Hello']); // Hello Kelly King
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(); // Hello Jon Kuperman
sayHelloKelly(); // Hello Kelly King