将“(0)”附加到此闭包函数的目的是什么

What is the purpose of appending "(0)" to this closure function?

本文关键字:闭包 函数 是什么      更新时间:2023-09-26

正如标题所述,在此代码截图(在此处找到)中附加(0);而不仅仅是();的目的是什么:

function runner (fns, context, next) {
  var last = fns.length - 1;
  (function run(pos) {
    fns[pos].call(context, function (err) {
      if (err || pos === last) return next(err);
      run(++pos);
    });
  })(0);
}

它大致相当于:

function runner (fns, context, next) {
  var last = fns.length - 1;
  function run(pos) {
    fns[pos].call(context, function (err) {
      if (err || pos === last) return next(err);
      run(++pos);
    });
  }
  run(0);
}

0 只是作为pos的第一个值传递给run() 的值 – 与递归run(++pos);相同(最好写为 run(pos + 1) )。

目的是将 0 作为值传递给 pos 参数。