concept apply and call method in category javascript
appears as: apply d call methods

This is an excerpt from Manning's book Secrets of the JavaScript Ninja, Second Edition.
This is a surprisingly common problem, and later in the chapter, you’ll see techniques for completely evading it. For now, let’s explore how to tackle it by examining how to explicitly set the function context by using the apply and call methods.
Listing 4.11. Using the apply and call methods to supply the function context
function juggle() { #A var result = 0; #A for (var n = 0; n < arguments.length; n++) { #A result += arguments[n]; #A } #A this.result = result; #A } #A var ninja1 = {}; #B var ninja2 = {}; #B juggle.apply(ninja1,[1,2,3,4]); #C juggle.call(ninja2, 5,6,7,8); #D assert(ninja1.result === 10, "juggled via apply"); #E assert(ninja2.result === 26, "juggled via call"); #E #A - The function “juggles” the arguments and puts the result onto whatever object is the function context. #B - These objects are initially empty and will serve as our test subjects. #C - Uses the apply method, passing ninja1 and an array of arguments #D - Uses the call method, passing ninja2 and a list of arguments #E - The tests show how the juggle result is placed on the objects passed to the methods. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[]"} !@%STYLE%@!