局部变量在闭包中丢失

Local variable lost in closure

本文关键字:闭包 局部变量      更新时间:2023-09-26

变量cont在以下情况下丢失:

    __factory.setupMenu = function(cont,input,multiSelect,exclusive,popMenu){               
        var __menu = {multiSelect:multiSelect};
        spotter.events.setEventTrigger(input,'change');
        __menu.exclusive = {inputs:[],values:exclusive||[],simpleValues:[]};
        alert(cont);//<-- is defined here
        window.popSelectComponent= cont;//<-- saved it globally to test reference
        return function(ajaxResult){
            var data = ajaxResult.template.response||[];
            var info = {},l=data.length;
            while(--l > -1){
                info[String(data[l].value)] = data[l].abbr||data[l].name;
            }
            var textTarget;
            alert(window.popSelectComponent);//<-- this is defined as expected
            alert(cont);//<-- is now undefined
            alert(input);//<-- this is defined as expected
            if(!(textTarget = cont.querySelector('[data-pop-selected]'))){textTarget = cont;}
if(!input.popSelectTemplate){   
                spotter.data.bindElementToInput(textTarget,input,function(content){
                    content = content.split(',');
                    var l=content.length;
                    while(--l > -1){
                        content[l] = info[content[l]];
                    }
                    content = content.join(',');
                    return (content.length ? content : 'ignore');
                });
            }
            else{
                var cont = document.createElement('SPAN');//<-- PROBLEM IS CAUSED HERE. HOISTING IS CAUSING CONT TO BE UNDEFINED AT CLOSURE START
                cont.className="multi-select";
                cont.appendChild(cont);
                //removal function
                var remove = (function(input){
                    return function(e){
                        var evt = e ? e:window.event;
                        if (evt.stopPropagation)    evt.stopPropagation();
                        if (evt.cancelBubble!=null) evt.cancelBubble = true;
                        if(input.value !== input.spotterPopSelectDefaultValue){ 
                            input.value = input.value.removeListValue(this.getAttribute('data-id'),',');
                            spotter.deleteElement(this);
                            if(input.value === '' && input.value !== input.spotterPopSelectDefaultValue){
                                input.value = input.spotterPopSelectDefaultValue;
                                input.eventTriggers['pop-select-change']();
                            }
                        }
                    };
                }(input));
                input.spotterPopMenuOptions = __menu;
                input.addEventListener('pop-select-change',(function(cont, info, template){ 
                    return function(){
                        var HTML = '';
                        this.value.split(',').forEach(function(val){
                            HTML += template.replace('$[ID]', val).replace('$[NAME]', info[val]);
                        });
                        cont.innerHTML = HTML;
                        spotter.castToArray(cont.children).forEach(function(el){ console.log('option el',el); el.addEventListener('click',remove,false); });
                        console.log('input.spotterPopMenuOptions',input.spotterPopMenuOptions);
                    }; 
                }(cont, info, input.popSelectTemplate.innerHTML)),false);
            }
....

因此,运行var func = __factory.setupMenu(...)({template:{}})我收到一条错误消息,指出cont未定义,而window.popSelectComponent按预期定义。我尝试更改 cont 的名称,认为我忽略了正在更改值但也没有用的东西。

运行函数后,我在最初创建此闭包的上下文中检查 cont 并且 cont 仍然被定义,因此据我所知,这不是丢失对象引用的问题。

也许一个高度简化的例子会使问题更加明显:

var outer = function(theVariable) {
  console.log("In the outer function, theVariable is", theVariable);
  var inner = function() {
    console.log("In the inner function, theVariable is", theVariable);
    if (false) {
      var theVariable = 2;
    }
  };
  inner();
}
outer(1)
In the outer function, theVariable is 1
In the inner function, theVariable is undefined
如您所见,在内部函数中声明了具有

相同名称的不同变量(即使未初始化(这一事实隐藏了外部函数中正确初始化的变量,否则该变量是可见的。

您可能会认为,由于变量是在块中声明的,因此不会影响函数的其他部分。 不,var是函数作用域,而不是块作用域。

此缺陷已在现代版本的 Javascript 中得到解决,并且 var 关键字已被 let 取代,后者具有您期望的块范围。 保留var是为了向后兼容,但不应在新代码中使用它。