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 代码
- // 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 代码
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 代码
下一篇: 怎么解决php遍历文件乱码的问题
推荐阅读
-
angularjs 源码解析之scope
-
AngularJs Scope详解及示例代码
-
JavaScript 作用域(Scope)详解
-
超宽Ctrl键!华硕ROG Strix Scope游戏键盘上市
-
AngularJS的ng-repeat指令与scope继承关系实例详解
-
AngularJS中$injector、$rootScope和$scope的概念和关联关系深入分析
-
对angularJs中controller控制器scope父子集作用域的实例讲解
-
Angular.Js之Scope作用域的学习教程
-
AngularJS中如何使用$parse或$eval在运行时对Scope变量赋值
-
AngularJS中监视Scope变量以及外部调用Scope方法