Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

<button id="loginbtn">QQ登陆</button>
    <script type="text/javascript">
        var div=8;
          var createLoginLayer=(function(){
            var div;
            return function(){
                if(!div){
                   alert("div不存在");
                }
                //return div;
             }
        })();
        document.getElementById("loginbtn").onclick=function(){
            createLoginLayer();
         }
    </script>
    
   各位上午好,在if语句中要判断div是否存在,根据作用域的查找规则,如果在局部函数中没有该变量,
查询就会向上进行,而在全局变量中已经有了var div=8;为啥还会返回"div不存在"的提示框呢?谢谢!



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

重新声明了div,没有赋值,相当于现在div为undefined。
题主所谓的"根据作用域的查找规则,如果在局部函数中没有该变量,查询就会向上进行",这里if判断时,已经找到了div(值为undefined),所以不会再往上查找。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...