JavaScript的变量作用域

JavaScript的变量分为全局变量和局部变量

全局变量(Global)

全局变量是指在任何地方都可以访问的变量,有两种情况

  • 在function外面声明,不论是否用var 关键字
  • 在function里面声明,不使用var关键字,当然声明的语句必须被执行才可以

局部变量(Local )
局部变量只能在被声明的function内部才能访问

  • 在function里面声明,使用var关键字

两点要注意的地方

先看代码

    alert(i); //输出undefined
    for (var i = 0; i < 1; i++){};
    alert(i); //输出1
  • JavaScript不存在语句作用域,在语句内定义的变量会扩散到语句外边, 例子中i在for语句中声明,但是在for语句的外面任然可以访问
  • 在for语句之前就可以访问到i,只不过这时候还没有被赋值

下面是一个比较完整的demo (出自:http://www.mredkj.com/tutorials/reference_js_intro_ex.html)

var globalVar1 = '(G1) global variable declared with var keyword';
globalVar2 = '(G2) global variable without var keyword';
var someBoolean = true;
if (someBoolean) {
  var globalVar3 = '(G3) global variable declared with var keyword inside if statement';
}

function sampleFunction() {
  var localVar1 = '(L1) local variable declared with var keyword';
  localVar2 = '(L2) local variable declared without var keyword';
  if (someBoolean) {
    var localVar3 = '(L3) local variable declared with var keyword inside if statement';
  }

  document.writeln('You can reference all local variables inside the same function the variables are declared.
'); document.writeln(localVar1 + '
'); document.writeln(localVar2 + '
'); document.writeln(localVar3 + '

'); document.writeln('You can reference all global variables inside any function.
'); document.writeln(globalVar1 + '
'); document.writeln(globalVar2 + '
'); document.writeln(globalVar3 + '

'); } sampleFunction(); document.writeln('Outside a function, you can only reference local variables that are not declared with the var keyword.
'); document.writeln('Commented out. Cannot reference (L1)
'); //document.writeln(localVar1 + '
'); document.writeln(localVar2 + '
'); document.writeln('Commented out. Cannot reference (L3)

'); //document.writeln(localVar3 + '
'); document.writeln('Outside a function, you can reference all global variables.
'); document.writeln(globalVar1 + '
'); document.writeln(globalVar2 + '
'); document.writeln(globalVar3);
posted @ 2011-07-05 10:05  KymoWang  阅读(460)  评论(2编辑  收藏  举报