Does apply have hidden functions?

             var currying = function (fn) {
                  var arg = []
                  return function () {
                      if (arguments.length == 0) {
                          return fn.apply(this, arg)
                      } else {
                          [].push.apply(arg, arguments)   //(a) ok
                          // arg.push(arguments)    //(b)  wrong,arg stores the entire arguments as a object
                          // arg.push(arguments[0])  //(c)  ok
                     }
                 }
            }
           var cost = (function () {
               var sum = 0
               return function () {
                   for (var i = 0, l = arguments.length; i < l; i++) {
                       sum += arguments[i]
                   }
                  return sum
              }
         })()

        var costCurrying = currying(cost)
        costCurrying(111)
        costCurrying(222)
        costCurrying(333)
        console.log(costCurrying())    //666
                   

I found the code for this structure in the Currying function,(a)stores arguments that were passed in only ,but (b) stores the entire Arguments object, including Callee and Symbol. I wonder if you could help me with this.

Hi @897479992, it does not actually store the entire arguments object; apply() just treats its 2nd argument like an array and, in this case, pushes each of the arguments elements to arg. Another way of writing it with modern syntax would be using the spread operator:

arg.push(...arguments)

With arg.push(arguments) OTOH you’d indeed just push the single arguments object itself, as you would do when using call() instead of apply().

Thanks, I understand. Previously I simply thought apply() just changed ‘this’ and then called ‘push method’ to pass arguments in as a whole

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.