Binding: Call, Apply, and Bind in JavaScript
Lets keep it simple so that you will not have to search again the difference among these methods.
In Simple Words:
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, with modification of the context.
context = this (or scope that has to be use)
That is it! Literally that is it.
Still not clear? Let's have a closer look at their prototype and usage.
Prototypes:
function.bind(context[, arg1[, arg2[, ...]]])function.apply(context, [arrayOfArguments])function.call(context, arg1, arg2, ...)
.bind():
function.bind(context[, arg1[, arg2[, …]]])
Arguments:
- context = the context which has to be bind with the calling function, this context will be used later.
- [, arg1[, arg2[, …]]] = all other optional arguments required by the calling function.
Returns: the bounded function, which will use the context (bounded above) and arguments.
.apply():
function.apply(context, [arrayOfArguments])
Arguments:
- context = the context which has to be use now with the calling function.
- [arrayOfArguments] = arguments required by the calling function passed in an array.
Returns: the result of calling the actual function with the specified context and arguments.
.call():
function.call(context, arg1, arg2, …)
Arguments:
- context = the context which has to be use now with the calling function.
- arg1, arg2, … = arguments required by the calling function (Note: these arguments are being passed without an array, unlike in .apply() ).
Returns: the result of calling the actual function with the specified context and arguments.