繁体   English   中英

局部变量在关闭时丢失

[英]Local variable lost in closure

变量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:{}})我收到一条错误消息,说明window.popSelectComponent的定义如预期的那样,cont是未定义的。 我试图更改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取代, let具有您所期望的块范围。 保留var是为了向后兼容,但您不应在新代码中使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM