what's the difference between 'call/apply' and 'bind' [duplicate] what's the difference between 'call/apply' and 'bind' [duplicate] javascript javascript

what's the difference between 'call/apply' and 'bind' [duplicate]


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


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


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);// orsomeFunction.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.)