Javascript 函数实现之前的下划线.js
有人能解释一下u0.before函数是如何实现的吗?因为我不太明白为什么内部Javascript 函数实现之前的下划线.js,javascript,underscore.js,Javascript,Underscore.js,有人能解释一下u0.before函数是如何实现的吗?因为我不太明白为什么内部times变量跟踪每个函数调用。它不应该在本地范围内,并像正常功能一样每次重置吗 函数前的u.代码: // Returns a function that will only be executed up to (but not including) the Nth call. _.before = function(times, func) { var memo; return function
times
变量跟踪每个函数调用。它不应该在本地范围内,并像正常功能一样每次重置吗
函数前的u.代码:
// 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;
};
};
//返回仅在第n次调用之前执行(但不包括)的函数。
_.before=函数(次,func){
var备忘录;
返回函数(){
如果(--次>0){
memo=func.apply(这是参数);
}
if(times键为func.apply(此为参数)
使匿名函数递归。
时间的作用域在内部匿名函数之外。调用closer时,执行时间,时间的作用域为之前的函数。由于名为闭包的概念,exa中返回的函数MPE“记住”创建它的环境。在这种情况下,它会同时记住时间
和func
参数,即使返回了参数
阅读有关闭包的更多信息:您需要这个