what's the difference between 'call/apply' and 'bind'

bennyrice picture bennyrice · Mar 28, 2013 · Viewed 14.8k times · Source
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?

Answer

Quentin picture Quentin · Mar 28, 2013

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).