繁体   English   中英

在这个更高级别的函数中,参数n从何而来?

[英]in this higher level function, where does the argument, n come from?

在下面的Eloquent Javascript第5章代码中,参数n的值从何而来?

为什么此函数返回任何内容 我想,我不想问一个具体的,陈词滥调的问题,但是我很困惑:此功能如何工作?

 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 

如您所见,在这里的回调中将n定义为参数:

repeat(3, function(n) {
//                 ^

让我们进入repeat功能:

function repeat(times, body) {
    for (var i = 0; i < times; i++) body(i);
    // We're calling our callback with i ^
}

在这里times将是3body将是我们的匿名函数(回调)。 因此,当我们调用body(i)我们实际上调用以下(切换n用了i ,因为我们调用body(i)

unless(i % 2, function() {
    console.log(i, "is even");
})

这是您展开的整个源代码:

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");
    }
}

变量n在传递给“重复”的回调方法中定义:

repeat(3,function(n){

除非在该回调函数中进行了其他修改(或使用“ var n = ...”定义),否则该值将一直存在于console.log调用的范围内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM