什么是block scope?

来源:互联网 发布:福州云顶网络智联 编辑:程序博客网 时间:2024/06/05 08:47

block scope:在java 中表示{ }之间定义的变量,常量,出了{ }变量就会消失。

    有函数块: void test1() {  }

            if 块 : if (true) {}

           for 块:for ()  {}

          while块:while(){ }

 javascript中:主要讲得是if,for,while块,如果函数里面定义这3个块,哪么块里的变量在函数里面任何地方都可以使用,所以导致javascript有块语法,但是无块作用域。

一、全局变量三种表示:

1、放在任何函数外面

    var foo = value;

2、给全局对象直接加一个属性.

          全局对象是一个容器,里面装满所有全局变量。In web browsers, window是全局对象名。

       window.foo = value;

3、foo = value;

  最好在函数开头定义所有变量,反正无块作用域。

二、块作用域,在java中,所有{ }里面声明的变量,外面是看不见。

  例如:有三个块作用域,test1函数for块定义的变量j,b,出了 for {}块就消失。 

下面以for(){} 块为例:   

 public  class TestBlock()

  {   

   void test1()
  {
    int i=5;
   for(int j=1;j<5;j++)
    {   
      int b=2;
    }
   System.out.println(“b"+b+",j"+j); //编译时通不过
  }
}

 但是在javascirpt块,没有块作用域的说法,在test1{ }里面for(){} 里面定义的变量,外面函数test1任何地方可以看见。  

var  TestBlock=function()
 {
    var test1=function(){
          var i=0;
          for(var j=0;j<=5;j++)
            {
             var a=j;    
           }   
          console.log(a,j);
        };  
    test1();
 };
   TestBlock();

结果:5 6 所以在javascript中无块作用域,变量在函数里面for,if,while 块定义的变量,函数任何地方都可见

三、javaScript不用块作用域,哪用什么作用域?函数作用域。

    块作用域:在一块里{ },变量,常量存在,出了块就消失

    函数作用域:在一个函数里定义的变量,常量,在函数里面任何地方可用,出了函数就消失。

四、名字空间的问题,java中用包(也就是文件夹的方式)解决名子冲突问题,哪javascript 怎么解决所有变量,常量,函数名冲突的问题?

    

参考文章:【1】http://www.programmerinterview.com/index.php/javascript/javascript-block-scope/

                  【2】 the good part



down vote

In a nutshell, Global variables cause (and more) the following issues.

1) Variable naming collisions - If you're working on a team and both yourself and your co-worker use the same variable name on the global scope, the variable defined last will overwrite the initial variable. This obvious can have devastating consequences.

2) Security - Specifically on the web, every user has access to the Window (or global) object. By putting variables on the global scope, you give any user the ability to see or change your variables.

3) Slower - This is arguably negligible, but it still exists. The way JavaScript variable lookups work is the JavaScript engine will do a lookup on the current scope the variable is being looked up in. If it can't find it, it will do a look up on the next parent scope. If it doesn't find it there, it will continue looking upward until it reaches the global object looking for that variable. If all of your variables are located on the global scope, the JavaScript engine will always have to go through every scope in order to finally reach the global scope to find the variable.