difference between call bind and apply in javascript 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])
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');
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();