concept apply in category javascript

appears as: pply
Secrets of the JavaScript Ninja, Second Edition

This is an excerpt from Manning's book Secrets of the JavaScript Ninja, Second Edition.

  • Via the function’s apply or call methods—skulk.call(ninja)or skulk.apply(ninja)
  • 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%@!

    We then set up two objects, ninja1 and ninja2, that we’ll use as function contexts, passing the first to the function’s apply method, along with an array of arguments, and passing the second to the function’s call method, along with a list of other arguments:

    juggle.apply(ninja1,[1,2,3,4]);
    juggle.call(ninja2, 5,6,7,8);

    Notice that the only difference between apply and call is how the arguments are supplied. In the case of apply, we use an array of arguments, and in the case of call, we list them as call arguments, after the function context. See figure 4.3.

    Figure 4.3. As the first argument, both the call and apply methods take the object that will be used as the function context. The difference is in the following arguments. apply takes only one additional argument, an array of argument values; call takes any number of arguments, which will be used as function arguments.

    After we’ve supplied our function contexts and arguments, we continue by testing! First, we check that ninja1, which was called via apply, received a result property that’s the result of adding up all the argument values (1, 2, 3, 4) in the passed array. Then we do the same for ninja2, which was called via call, where we check the result for arguments 5, 6, 7, and 8:

    assert(ninja1.result === 10, "juggled via apply");
    assert(ninja2.result === 26, "juggled via call");