Apply vs Call vs Bind Examples
Call
var person1 = {firstName: 'pranay', lastName: 'soni'};
var person2 = {firstName: 'test_f', lastName: 'test_l'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.call(person1, 'Hello'); // Hello pranay soni
say.call(person2, 'Hello'); // Hello test_f test_l
Apply
var person1 = {firstName: 'pranay', lastName: 'soni'};
var person2 = {firstName: 'test_f', lastName: 'test_l'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.apply(person1, ['Hello']); // Hello pranay soni
say.apply(person2, ['Hello']); // Hello test_f test_l
Bind
var person1 = {firstName: 'pranay', lastName: 'soni'};
var person2 = {firstName: 'test_f', lastName: 'test_l'};
function say() {
console.log('Hello ' + this.firstName + ' ' + this.lastName);
}
var sayHelloPranay = say.bind(person1);
var sayHelloTest = say.bind(person2);
sayHelloPranay(); // Hello pranay soni
sayHelloTest(); // Hello test_f test_l
When To Use Each
Call and apply are pretty interchangeable.
Just decide whether it’s easier to send in an array or a
comma separated list of arguments.
I always remember which one is which by remembering that Call is for
comma (separated list) and Apply is for Array.
Bind is a bit different. It returns a new function.
Call and Apply execute the current function immediately.
No comments:
Post a Comment