Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript call() & apply() vs bind()?

I already know that apply and call are similar functions which setthis (context of a function).

The difference is with the way we send the arguments (manual vs array)

Question:

But when should I use the bind() method ?

var obj = {   x: 81,   getX: function() {     return this.x;   } };  alert(obj.getX.bind(obj)()); alert(obj.getX.call(obj)); alert(obj.getX.apply(obj)); 

jsbin

like image 316
Royi Namir Avatar asked Mar 16 '13 21:03

Royi Namir


People also ask

What does call () do in JavaScript?

The call() allows for a function/method belonging to one object to be assigned and called for a different object. call() provides a new value of this to the function/method. With call() , you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.

What is the difference between call () and apply ()?

The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.

What is the use of call and apply in JavaScript?

Apply() Method in JavaScript The apply() method does the exact same as call() . The difference is that call() accepts an argument list, but apply() accepts an array of arguments.


1 Answers

Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context.

Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.

I do this a lot:

function MyObject(element) {     this.elm = element;      element.addEventListener('click', this.onClick.bind(this), false); };  MyObject.prototype.onClick = function(e) {      var t=this;  //do something with [t]...     //without bind the context of this function wouldn't be a MyObject     //instance as you would normally expect. }; 

I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.

A simple, naive implementation of bind would be like:

Function.prototype.bind = function(ctx) {     var fn = this;     return function() {         fn.apply(ctx, arguments);     }; }; 

There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.

like image 64
Chad Avatar answered Oct 12 '22 02:10

Chad