Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript 'curry', need some explanations on this code

Tags:

javascript

I am reading the book "JavaScript-The Good Parts", in chapter 4.14 Curry, the book gives the following example:

Function.method('curry', function(){
    var slice = Array.prototype.slice,
        args = slice.apply(arguments), //1st-arguments
        that=this;

    return function(){
       return that.apply(null, args.concat(slice.apply(arguments))); //2nd-arguments
    }
})

var add1=add.curry(1);
document.writeln(add1(6)); // 7

I have two questions on this code:

  1. There are two places using 'arguments'. In the method invoking in the last two lines code, is it so that '1' goes to the 1st-arguments and '6' goes to the 2nd-arguments?

  2. There is a line of code apply(null, args.concat(slice.apply(arguments))), why does it apply(null,...) here?, what is the sense to apply a argument to a null object?

like image 806
Mellon Avatar asked Mar 28 '11 08:03

Mellon


1 Answers

There are two places using 'arguments'. In the method invoking in the last two lines code, is it so that '1' goes to the 1st-arguments and '6' goes to the 2nd-arguments?

Yes, 1 is part of arguments of the outer function, while 6 goes the arguments in the inner function. The inner function can capture all other variables in a closure except for arguments and this, which have a special meaning inside a function, hence are not part of that closure. So that, and args are captured, but not arguments.

There is a line of code apply(null, args.concat(slice.apply(arguments))), why does it apply(null,...) here?, what is the sense to apply a argument to a null object?

Invoking a method with a null context will simply set the this value to the global object. In the case it seems the author does not care what that context is.

like image 152
Anurag Avatar answered Oct 27 '22 18:10

Anurag