What is apply invocation pattern in Javascript in reference to function invocation patterns and how can I use it?
What are the benefits of using this invocation pattern.
What is apply invocation pattern in Javascript in reference to function invocation patterns and
Share
The use of
applyis related to the function context (thethiskeyword) and argument passing.First, I think you should know in which cases the
thiskeyword is implicitly set:1- When a function is called as a method (the function is invoked as member of an object):
2- A normal function call:
3- When the
newoperator is used:Here is when
applyandcallcome, those methods let you set explicitly the context when you invoke a function, eg.:In the above code, when the
testfunction is called setting thethiskeyword to a String ('Hello'), and passing theaargument (' world.').Both,
callandapplychange the context of the executing function (thethiskeyword) inside the called function, but the difference between them is that withapply, you can send an Array or an Array-like object as the arguments of the function to be executed, which is extremely useful, for example:That can avoid some very hacky, bad (and common)
evalcalls like:Another example, the
Math.maxandMath.minmethods, those methods can receive an arbitrary number of arguments like:But what if you have an Array of numbers?
Also note that when
nullorundefinedis used as thethisargument withcallorapply, thethisobject will refer to the Global object (similar to the case #2, normal function invocation).For the
Math.maxexample, the context is not really relevant, since they are just like “static” methods, thethiskeyword is not used internally…