为什么n减少?

时间:2017-03-05 01:18:44

标签: javascript

所以我试图写一个简单的Factory函数来返回一个接受回调的函数。

此回调function (func, n)需要2个参数,第一个是函数,第二个是数字 它所做的只是每次都func递增n func是函数表达式shell,它调用回调并返回结果n

console.log中,b4表示在调用回调之前,after表示之后。

我感到困惑的是,为什么after的输出会减少?



var factory = function (cb) {

  var shell = function (n) {
    console.log('b4: ' + n);
    var rs = 0;
    if (n && n < 5) {
      rs = cb(shell, n);
      console.log('after: ' + n + ' // huh?');
      console.log('return rs: ' + rs);
      return rs;
    }
    console.log('return n: ' + n);
    return n;
  };
  return shell;
}

var a = factory(function (func, n) {
  return func(n + 1);
});
console.log('a: ' + a(1));
&#13;
&#13;
&#13;

Jsbin:https://jsbin.com/raqiwom/edit?js,console

1 个答案:

答案 0 :(得分:0)

因为它是一个递归结构。 “rs = cb(shell,n);”在“console.log('after:'+ n +'// huh?');”之前执行,并且它调用“shell”函数。

相关问题