【问题标题】:How do I freeze a function's variables in a closure?如何在闭包中冻结函数的变量?
【发布时间】:2012-08-28 11:48:19
【问题描述】:

我正在开发一个支持重复事件的日历,因此预期的行为是,当有人在某一天选中一项活动的“完成”复选框时,它会隐藏当天的活动实例,而其他活动则保持不变。

实际看到的行为是,当有人选中任何复选框时,它会删除该活动的最后一天的实例,我很确定这是因为函数正在访问闭包中循环的最新变量,而不是这些变量在运行时所持有的值。相关代码sn-p为:

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 函数访问它在创建时而不是在循环退出时拥有的变量的最佳选择是什么?

谢谢,

【问题讨论】:

    标签: javascript html google-chrome closures


    【解决方案1】:

    你没有在你的代码中使用任何闭包。 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多