Call, Apply, and Bind
December 08, 2018
Three things so similar it’s hard to keep them apart. Been thinking how I’m not as familiar with bind
as I should be, so diving in and realized I should extend it to call
/apply
.
Call
Function.prototype.call(thisArg, arg1, arg2, ...)
MDN Link
Take the first argument as the context and then a list of arguments for the function. Essentially the same thing as apply
, just with a list of arguments.
Apply
Function.prototype.apply(thisArg, [arg1, arg2, ...])
MDN Link
Take the first argument as the context and then an array of arguments for the function. Essentially the same thing as call
, just with an array of arguments.
Bind
function.bind(thisArg, arg1, arg2, ...)
MDN Link
Given a defined function, provide the context and prepend the arguments when the function is invoked. Useful when you want to call a function later with a different context.