Underscore.js的.before函数实现

3

有人能解释一下 _.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;
    };
  };

谢谢。

你需要这个 https://dev59.com/6XVD5IYBdhLWcg3wBm5h - Maxx
2个回答

0

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


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接