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:
-
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?
-
There is a line of code
apply(null, args.concat(slice.apply(arguments))), why does itapply(null,...)here?, what is the sense to apply a argument to a null object?
Yes, 1 is part of
argumentsof the outer function, while 6 goes theargumentsin the inner function. The inner function can capture all other variables in a closure except forargumentsandthis, which have a special meaning inside a function, hence are not part of that closure. Sothat, andargsare captured, but notarguments.Invoking a method with a null context will simply set the
thisvalue to the global object. In the case it seems the author does not care what that context is.