In the following code from ch 5 of Eloquent Javascript , where does that value of the argument n come from?
Why does this function return anything . I guess, I hate to ask a unspecific, cliche question, but I am baffled: How does this function work?
function unless(test, then) { if (!test) then(); } function repeat(times, body) { for (var i = 0; i < times; i++) body(i); } repeat(3, function(n) { unless(n % 2, function() { console.log(n, "is even"); }); }); // → 0 is even // → 2 is even
As you can see n
is defined as a parameter in the callback here:
repeat(3, function(n) {
// ^
Let's go into the repeat
function:
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
// We're calling our callback with i ^
}
Here times
will be 3
and body
will be our anonymous function (callback). Hence when we call body(i)
we actually call the following (switched n
out with i
, as we're calling body(i)
):
unless(i % 2, function() {
console.log(i, "is even");
})
Here's your entire source unwrapped:
var times = 3;
for (var i = 0; i < times; i++) {
var n = i; // We're renaming "i" (from body(i)) to "n" (in function(n))
if (!(n % 2)) {
console.log(n, "is even");
}
}
The variable n is defined in the callback method you are passing to "repeat":
repeat(3,function(n){
unless otherwise modified inside that callback function (or defined using "var n = ..." that value will persist in the scope all the way to the console.log call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.