Android App

TechLogic
In simple words,

  • Call invokes the function and allows you to pass in arguments one by one.
  • Apply invokes the function and allows you to pass in arguments as an array.
  • Bind returns a new function, allowing you to pass in a this array and any number of arguments.

Call and apply are some what interchangeable. We can decide on basis of whether it’s easier to send in an array or a comma separated list of arguments to a function.

A bind function is basically which binds the context of something and then stores it into a variable for execution at a later stage. A Bind is different than Call and Apply as it returns a new function. Whereas Call and Apply execute the current function immediately. Bind doesn't execute function immediately, but returns wrapped apply function.

Call Example:

var person1 = {firstName: 'Harry', lastName: 'Potter'};
var person2 = {firstName: 'Kane', lastName: 'Smith'};

function say(greeting) {
    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

say.call(person1, 'Hello'); // Hello Harry Potter
say.call(person2, 'Hello'); // Hello Kane Smith

Apply Example:


 var person1 = {firstName: 'Harry', lastName: 'Potter'};
 var person2 = {firstName: 'Kane', lastName: 'Smith'};

 function say(greeting) {
    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
 } 
say.apply(person1, ['Hello']); // Hello Harry Potter
say.apply(person2, ['Hello']); // Hello Kane Smith

Bind Example:

 var person1 = {firstName: 'Harry', lastName: 'Potter'};
 var person2 = {firstName: 'Kane', lastName: 'Smith'};

function say() {
    console.log('Hello ' + this.firstName + ' ' + this.lastName);
}

var sayHelloHarry = say.bind(person1);
var sayHelloKane = say.bind(person2);

sayHelloHarry();   // Hello Harry Potter
sayHelloKane();    // Hello Kane Smith


The basic difference between Call, Apply and Bind ==> Bind will be used if you want your execution context to come later in the picture.

Trick to remember, Call is for comma separated list and Apply is for Array.






Post a Comment