Back

js变量作用域 javascript variable scopes

发布时间: 2015-02-21 10:03:00

refer to:  http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript

作者说的好: 作用域通常用来判断一个JS程序员的水平.  

( 这里还有个小测试, 很有意思: http://madebyknight.com/javascript-scope/)

下面是接近9个例子,说明了 变量在不同 scope下的表现, 基本上跟ruby 一样, 对于 class, scope, try-catch的定义, 都是 在对应的scope 之内生效. 不同的是,多了 prototype 以及

// 1. global scoped variable: 全局变量 a:
var a = 1;
function one() {
  console.info(a)
}

// 2. 
function two(a ){
  console.info(' in three, before a=2: ' + a)
  a = 2;
  console.info(' in three, after a=2: ' + a)
}

function three(){
  console.info(' in three, before a=3: ' + a)
  a = 3 ;
  console.info(' in three, after a=3: ' + a)
}

function four(){
  console.info(' in four, before a=4: ' + a)
  if(true) a = 4;
  console.info(' in four, after a=4: ' + a)
}

function five(){
  console.info(' in five, before this.a=5: ' + a)
  this.a = 5;
  console.info(' in five, after this.a=5, a: ' + a)
  console.info(' in five, after this.a=5, this.a:' + this.a)
}

var six = ( function(){
  var foo = 6;
  return function(){
    console.info(foo);
  }
}
)();


function seven(){
  this.a = 7;
  console.info("--- in seven, this.a" + this.a);
}

seven.prototype.a = -1;
seven.prototype.b = 8;
console.info(' new seven().a : ' + new seven().a)  
# --- in seven, this.a7
#  new seven().a : 7
console.info(' new seven().b : ' + new seven().b)  
# --- in seven, this.a7
# new seven().b : 8

var x = 888;
(function(){
  console.log('before set ,x: ' + x);
  # before set ,x: undefined
  var x = 10;
  console.log('after set, x: ' + x);
  # after set, x: 10
})();


var e = 9;
console.log('before try, e is: ' + e);
# => before try, e is: 9
try {
  throw 99;
} catch (e){
  console.log(' in catch , e: ' + e)
  # =>  in catch , e: 99
}
console.log('after try, e is: ' + e);
# => after try, e is: 9

one(); 
two();
three();
four();
five();
six();
seven();


# 下面是结果.... 最好自己手动运行,体会一下.
1
 in three, before a=2: undefined
 in three, after a=2: 2
 in three, before a=3: 1
 in three, after a=3: 3
 in four, before a=4: 3
 in four, after a=4: 4
 in five, before this.a=5: 4
 in five, after this.a=5, a: 4
 in five, after this.a=5, this.a:5
6

Back