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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With