Scope is a tricky feature of JavaScript.(棘手的问题) All object-oriented programming languages have some
form of scope; it just depends on what context a scope is kept within. In JavaScript, scope is kept within functions, but not within blocks (such as while, if, and for statements). The end result could be some code whose results are seemingly strange (if you’re coming from a blockscoped language). Listing 2-10 shows an example of the implications of function-scoped code。
在js中,scope是由函数划分的,而不是由块来划分的(如while,if ,for)这样导致的结果是某些代码不会理解(如果你曾经使用过用快划分域的语言)。如下是一个根据函数划分作用域而来的代码:
// Set a global variable, foo, equal to test var foo = "test"; // Within an if block if ( true ) { // Set foo equal to 'new test' // NOTE: This is still within the global scope! var foo = "new test"; } // As we can see here, as foo is now equal to 'new test' alert( foo == "new test" ); // Create a function that will modify the variable foo function test() { var foo = "old test"; } // However, when called, 'foo' remains within the scope // of the function test(); // Which is confirmed, as foo is still equal to 'new test' alert( foo == "new test" );
都是输出true true。
the variables are within the global scope. An interesting aspect of browser-based JavaScript is that all globally scoped variables are actually just properties of the window object. Though some old versions of Opera and Safari don’t, it’s generally a good rule of thumb to assume a browser behaves this way. Listing 2-11 shows an example of
this global scoping occurring.
一个有趣的事实是基于浏览器的一个有趣的特性是变量其实都是window对象的属性(property).尽管某些早期版本的opera和safari并非如此,
但还是可以大致认为浏览器都遵循此规则。下面展示了这种用法:
// A globally-scoped variable, containing the string 'test' var test = "test"; // You'll notice that our 'global' variable and the test // property of the the window object are identical alert( window.test == test );
Finally, let’s see what happens when a variable declaration is misdefined. In Listing 2-12a 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 variableisn’t explicitly defined, it will become defined globally, even though it is only used within the context of the function scope.
Example of Implicit Globally Scoped Variable Declaration // A function in which the value of foo is set function test() { foo = "test"; } // Call the function to set the value of foo test(); // We see that foo is now globally scoped alert( window.foo == "test" );
但是我在chrome显示的是false,不知为什么。
As should be apparent by now, even though the scoping in JavaScript is not as strict asa block-scoped language, it is still quite powerful and featureful. Especially when combinedwith the concept of closures, discussed in the next sectio n, JavaScript reveals itself as a powerful scripting language.