什么是block scope?

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



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.

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值