The Scope Chain
javascript is a lexically scoped language: the scope of variable can be thought of as the set of source code lines for which the variable is defined. global variables are defined throughout the program. local variables are defined throughout the function in which they are declared, and also within any functions nested within that function.
if we think of local variables as properties of some kind of implementation-defined object, then there is another way to think about variable scope. every chunk of javascript code (global code or functions) has a scope chain associated with it. this scope chain is a list or chain of objects that defines the variables that are "in scope" for that code. when javascript needs to look up the value of a variable x (a process called variable resolution), it starts by looking at the first object in the chain. if that object has a property named x, the value of that property is used. if the first object does not have a property named x, javascript continues the search with the next object in the chain. if the second object does not have a property named x, the search moves on to the next object, and so on. if x is not a property of any of the objects in the scope chain, then x is not in scope for that code, and a referenceerror occurs.
in top-level javascript code (i.e., code not contained within any function definitions), the scope chain consists of a single object, the global object. in a non-nested function, the scope chain consists of two objects. the first is the object that defines the function's parameters and local variables, and the second is the global object. in a nested function, the scope chain has three or more objects. it is important to understand how this chain of objects is created. when a function is defined, it stores the scope chain then in effect. when that function is invoked, it creates a new object to store its local variables, and adds that new object to the stored scope chain to create a new, longer, chain that represents the scope for that function invocation. this becomes more interesting for nested functions because each time the outer function is called, the inner function is defined again. since the scope chain differs on each invocation of the outer function, the inner function will be identical on each invocation of the outer function, but the scope chain associated with that code will be different.
下一篇: 02JavaScript用法
推荐阅读
-
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方法
-
贝尔链(Baer Chain):SH-DPOS机制可以让每个人都成为超级
-
Spring入门(五):Spring Bean Scope讲解