如何冻结函数's在闭包中的变量
How do I freeze a function's variables in a closure?
我正在开发一个支持重复出现的日历,因此,当有人在某一天选中某个活动的"完成"复选框时,它会隐藏当天的活动实例,而不影响其他活动。
实际可见的行为是,当有人选中任何复选框时,它会删除该活动最后一天的实例,我很确定这是因为函数正在访问闭包中循环的最新变量,而不是运行时这些变量所持有的值。相关代码片段为:
for(var index = 0; index < elements.length; ++index)
{
var split_id = elements[index].id.split('_');
var id = Number(split_id[1]);
var day = split_id[2];
var date = split_id[3];
var month = split_id[4];
var year = split_id[5];
elements[index].onclick = function()
{
alert(id + '_' + day + '_' + date + '_' + month + '_' + year);
if (calendar[id][2].indexOf(id + '_' + day + '_' + date + '_' + month + '_' + year) === -1)
{
calendar[id][2][calendar[id][2].length] = id + '_' + day + '_' + date + '_' + month + '_' + year;
}
save_all();
update_calendar_display();
}
}
让onclick函数访问创建时的变量,而不是退出循环时的变量的最佳选项是什么?
谢谢,
u在ur代码中没有使用任何闭包。for循环没有定义作用域。试试这个
function clickFunction(id, date, day, month, year) {
return function() {
alert(id + '_' + day + '_' + date + '_' + month + '_' + year);
if (calendar[id][2].indexOf(id + '_' + day + '_' + date + '_' + month + '_' + year) === -1) {
calendar[id][2][calendar[id][2].length] = id + '_' + day + '_' + date + '_' + month + '_' + year;
}
save_all();
update_calendar_display();
}
}
然后
elements[index].onclick = clickFunction(id, date, day, mo)
相关文章:
- 子类访问父类's闭包变量
- 构造函数函数闭包变量
- 如何冻结函数's在闭包中的变量
- 使变量可用于不带闭包的异步调用
- 局部变量在闭包中丢失
- 其中是闭包中存储的变量-堆栈或堆
- javascript闭包:保护内部变量
- Javascript:附加字符串中的事件,闭包中的变量求值
- "可变变量可从闭包“”访问;在传递给Array.prototype.every的函数中
- JavaScript闭包和变量引用
- Javascript分析之谜 - 闭包变量
- 对闭包变量的更改是否在使用闭包的回调中可见
- 使用object.assign()添加到对象中的getter发现闭包变量的值错误
- Javascript:为什么对闭包变量的访问可能很慢
- 模块中未更新Nodejs闭包变量
- node.js捕获闭包变量
- Javascript中绑定闭包变量
- 函数外部的Javascript闭包变量访问
- 回调函数访问闭包变量
- 为什么我的闭包变量在使用$后被清除.每个都使用JSON数据