zoukankan      html  css  js  c++  java
  • Javascript没有块级作用域

                                       --摘自《Javascript权威指南》

      Javascript没有块级作用域。函数中声明的所有变量,无论是在哪里声明的,在整个函数中它们都是有定义的。在下面的代码中,变量i、j和k的作用域是相同的,它们三个在整个函数体中都有定义。

      

       function test(o){
    var i=0;               //i is defined throughout function
    if(typeof o=="object"){  
      var j=0;            //j is defined everywhere,not just block
         for(var k=0;k<10;k++){    //k is defined everywhere,not just loop
       document.write(k);
         }
         document.write(k);      //k is still defined:prints 10
       }
       document.write(j);         //j is defined,but may not be initalized
    }

        这一规则(即函数中声明的所有变量在整个函数中都有定义)可以产生惊人的结果。下面的代码说明了这一点:

      

    var scope="global";
    function f(){
      alert(scope);    //Displays "undefined",not "global"
      var scope="local";   //Variable initialzed here,but defined everywhere
      alert(scope)
    }
    f();

      可能认为对alert()的第一次调用会显示出“global”,因为声明局部变量的var语句没有被执行。但是,由于这个作用域的限制,输出的并不是“global"。局部变量在整个函数体内都是有定义的,这就意味着在整个函数体中都隐藏了同名的全局变量。虽然局部变量在整个函数体中都是有定义的,但是在执行var语句之前,它是不会被初始化的,这个例子说明了为什么将所有的变量声明集中起来放置在函数的开头是一个好的编程习惯。

  • 相关阅读:
    [hihocoder1509][异或排序]
    [hdu6148][Valley Numer]
    [hdu2089][不要62]
    [luoguU42591][小T的绝对值]
    [luogu2073][送花]
    [bzoj4709][柠檬]
    [luogu2114][起床困难综合症]
    [codevs3342][绿色通道]
    [luoguU42591][小T的面试题]
    [noip][2014]
  • 原文地址:https://www.cnblogs.com/hwpayg/p/j1.html
Copyright © 2011-2022 走看看