32
var obj = {
   x: 81,
   getX: function() { 
     console.log( this.x) 
   }
};
var getX = obj.getX.bind(obj);//use obj as 'this';
getX();//81
var getX = function(){
  obj.getX.apply(obj); 
}
getX();//also 81

The use of bind and call/apply look very similar, I want to know what's the difference between them.The two getX Function above is the same?

bennyrice
  • 323
  • 1
  • 3
  • 7
  • Check http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply or http://stackoverflow.com/questions/15455009/js-call-apply-vs-bind – Rakesh Mar 28 '13 at 09:08

3 Answers3

39

bind returns a function which will act like the original function but with this predefined. It is usually used when you want to pass a function to an event handler or other async callback.

call and apply will call a function immediately letting you specify both the value of this and any arguments the function will receive.

Your second example defines an anonymous function which calls apply. This is a common pattern; bind provides a standard implementation of that which allows you to do it with a simple function call (thus being quicker and easier to write).

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • 4
    Also, you can specify arguments in the `bind()` call that will be prepended to the argument list when you call the resulting function, e.g. `function add(a,b){return a+b}; var plus5=add.bind(null,5); console.log(plus5(6) /*11*/)` – thejh Mar 28 '13 at 09:05
34

.call() - calls the same function with the specified arguments

.apply() - calls the same function with the arguments specified in an array

.bind() - creates a new function with the same function body, with a preset value of this (the first argument) and returns that function.

In all cases, the first argument is used as the value of this inside the function.

techfoobar
  • 61,046
  • 13
  • 104
  • 127
5

The difference is how you make the call. If you've used bind to get back a function with a bound this value, you just call the function:

getx();

If you don't have a bound function, and you want to set this, you do so with call or apply:

someFunction.call(objectToUseAsThis, arg1, arg2);
// or
someFunction.apply(objectToUseAsThis, [arg1, arg2]);

Note that if you have a bound function (like your getX), using call on it is pointless, because the this you supply will just get overridden by the bound this. (Using apply might still be useful, if you have an array of values you want to ass as arguments.)

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639