欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascipt scope

程序员文章站 2022-03-14 09:13:35
...

From Apress ProJavaScriptTechniques

In JavaScript, scope is kept within functions, but not within blocks (such as while, if, and for statements).

js 代码
 
  1. // Set a global variable, foo, equal to test  
  2. var foo = "test";  
  3. // Within an if block  
  4. if ( true ) {  
  5. // Set foo equal to 'new test'  
  6. // NOTE: This is still within the global scope!  
  7. var foo = "new test";  
  8. }  
  9. // As we can see here, as foo is now equal to 'new test'  
  10. alert( foo == "new test" );  
  11. // Create a function that will modify the variable foo  
  12. function test() {  
  13. var foo = "old test";  
  14. }  
  15. // However, when called, 'foo' remains within the scope  
  16. // of the function  
  17. test();  
  18. // Which is confirmed, as foo is still equal to 'new test'  
  19. alert( foo == "new test" );  

An interesting aspect of browser-based JavaScript is that all globally scoped variables are actually just properties
of the window object.

js 代码
  1. // A globally-scoped variable, containing the string 'test'   
  2. var test = "test";   
  3. // You'll notice that our 'global' variable and the test   
  4. // property of the the window object are identical   
  5. alert( window.test == test );  

In Listing 2-12 a value is assigned to a variable (foo) within the scope of the test() function. However, nowhere in Listing 2-12 is the scope of the variable actually declared (using var foo). When the foo variable isn’t explicitly defined, it will become defined globally, even though it is only used within the context of the function scope.

Listing 2-12

js 代码
  1. // A function in which the value of foo is set   
  2. function test() {   
  3. foo = "test";   
  4. }   
  5. // Call the function to set the value of foo   
  6. test();   
  7. // We see that foo is now globally scoped   
  8. alert( window.foo == "test" );  
相关标签: JavaScript