12 months ago

Found a really good example that explains the differences among bind, call and apply.

Both call and apply attaches this into function and executes the function immediately:

var person = {  
  name: "James Smith",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

person.hello.call(person, "world"); // output: "James Smith says hello world"

The difference is that apply can take in an array as the parameters but call has to list them individually:

call(obj, 'arg1', 'arg2', 'arg3');

var args = ['arg1', 'arg2', 'arg3'];
apply(obj, args);

bind only attaches this with a function but id does not execute the function:

var person = {  
  name: "James Smith",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

var helloFunc = person.hello.bind(person);
helloFunc("world");  // output: "James Smith says hello world"

You can also pass parameters to bind:

bind(obj, arg1, arg2 ,arg3);

bind is often used to express the intention of "this function is invoked with a particular this".

← JavaScript the value of this inside closure JavaScript the value of this inside a function →
 
comments powered by Disqus