2006-12-28
javascipt scope
关键字: javascriptFrom Apress ProJavaScriptTechniques
In JavaScript, scope is kept within functions, but not within blocks (such as while, if, and for statements).
js 代码
- // 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" );
An interesting aspect of browser-based JavaScript is that all globally scoped variables are actually just properties
of the window object.
js 代码
- // 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 );
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 代码
- // 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" );
- 11:01
- 浏览 (792)
- 评论 (0)
- 分类: javascript
- 相关推荐
发表评论
- 浏览: 91620 次

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
Tapestry5-如何在根目录下 ...
o,是我看的不仔细。不过我都是放在class相对应的资源包中。
-- by KorbenZhang -
Tapestry5-如何在根目录下 ...
文章提到的是组件类的模板,页面类默认是在根目录的。
-- by tapestry -
Tapestry5-如何在根目录下 ...
过时了,T5已经把tml文件放在根目录了。
-- by KorbenZhang -
Tapestry5开发系列:如何 ...
我删掉了依赖,加了servlet还是不行,jetty就是不起来,说没找到logg ...
-- by leegorous -
Tapestry5每日播报(20080 ...
非常支持.
-- by biaoming






评论排行榜