2012年3月11日星期日

javascript函数中变量的范围


代码 
  1. var first = 'hi there';  
  2. var first = (function() {  
  3.     console.log("first", first); // undefined  
  4.     var first = "hello world";  
  5. })();  
  6. //相当于  
  7. var first = 'hi there';  
  8. var first = (function() {  
  9.     var first;//the variable declaration moved to the top   
  10.     console.log("first", first); // undefined  
  11.     var first = "hello world";  
  12. })();  
  13.   
  14. // second test case  
  15. var second = 'hi there';  
  16. var second = (function() {  
  17.     console.log("second", second ); // "hi there"  
  18.     // here, we DO NOT declare a local "second" variable  
  19. })();  
  20.   
  21. // in the second test case, we don't declare the local variable, so the console.log call refers to the global variable and the value is not "undefined"  
  22. //link:http://jsfiddle.net/pomeh/ynqBs/  

没有评论:

发表评论