underscore.js.函数实现前

underscore.js .before function implementation

谁能解释一下 _.before 函数是如何实现的,因为我不太明白为什么内部 times 变量会跟踪每个函数调用。它不应该在本地范围内并且每次都像正常功能一样重置吗?

_.before 函数的代码:

  // Returns a function that will only be executed up to (but not including) the Nth call.
  _.before = function(times, func) {
    var memo;
    return function() {
      if (--times > 0) {
        memo = func.apply(this, arguments);
      }
      if (times <= 1) func = null;
      return memo;
    };
  };

谢谢。

关键是func.apply(this, arguments)使匿名函数递归。 times 的范围在内部匿名函数之外。当调用 closer 时 --times 被执行,times 的作用域是 before 函数。

由于名为 closures 的概念,您示例中返回的函数 "remembers" 创建它的环境。在这种情况下,它会记住 timesfunc 参数,即使它已返回。

阅读更多关于闭包的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures