带有函数参数数组的闭包
Closures with arguments array of function
看看 Leaflet API 中的代码
迷失在争论和关闭中。
我的参数的第二个日志输出是一个空数组。在第一个日志中应该不一样。
limitExecByInterval: function (fn, time, context) {
var lock, execOnUnlock;
// Log output 1
console.log(arguments);//[foo(), 10000, Window a.html]
return function wrapperFn() {
var args = arguments;
if (lock) {
execOnUnlock = true;
return;
}
lock = true;
setTimeout(function () {
lock = false;
if (execOnUnlock) {
wrapperFn.apply(context, args);
execOnUnlock = false;
}
}, time);
//Log output 2
console.log(args) //[]
fn.apply(context, args);
};
},
在第一个日志中应该不一样。
不。每个函数都有自己的arguments
对象。第二个console.log
调用将记录传递给wrapperFn
的参数,这在您的测试中似乎没有收到任何参数。
这是因为参数是函数内部的关键字,其行为不像普通变量。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
您需要将参数存储在另一个变量中才能获得所需的行为
limitExecByInterval: function (fn, time, context) {
var lock, execOnUnlock;
// Log output 1
console.log(arguments);//[foo(), 10000, Window a.html]
var myArgs = arguments ;
return function wrapperFn() {
var args = myArgs; /* not using the keyword 'arguments' here */
if (lock) {
execOnUnlock = true;
return;
}
lock = true;
setTimeout(function () {
lock = false;
if (execOnUnlock) {
wrapperFn.apply(context, args);
execOnUnlock = false;
}
}, time);
//Log output 2
console.log(args) //[] This will print an array now.
fn.apply(context, args);
};
},
相关文章:
- JavaScript闭包和返回数组元素
- 从数组中调用方法和闭包
- 为什么这个 JavaScript 闭包数组保留旧值
- 带有函数参数数组的闭包
- 创建带有回调的动态 JSON 数组(内部闭包问题)
- 使用闭包编译器类型检查数组内容
- 在闭包中公开数组的状态,而不允许从外部对其进行编辑
- 数组中jQuery元素的常见JavaScript闭包问题
- 带有节点数组的Javascript闭包
- 实现闭包以将数组索引“携带”到另一个数组
- 使用数组的javascript中的闭包
- 返回数组的闭包
- 谷歌闭包编译器类型注释数组
- 如何在加载后将媒体变量添加到数组时不改变它们.闭包
- 在javascript中创建数组并在闭包内追加值
- 为什么谷歌闭包编译器警告数组的长度
- for循环中的Ajax不会返回数组位置的正确值,尽管闭包绑定了当前值位置的范围
- 使用循环在数组中存储闭包函数
- Javascript数组和闭包
- 使用闭包传递数组值