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 it apply(null,...)
here?, what is the sense to apply a argument to a null object?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With