as3的作用域 让人感觉有点乱,不知道改如何专业的解释,最近一直在看 python 源码分析,受了些启发。也许as3也遵守这种静态作用域 规则,感觉所有的动态语言都有异曲同工之妙吧。
静态作用域 (static scope,也叫lexical scope,字面作用域),是一种根据语言文本的位置确定变量引用的规则。我从wikipedia上找到一个解释:
With static scope, a variable always refers to its top-level environment. This is a property of the program text and unrelated to the runtime call stack . Because matching a variable to its binding only requires analysis of the program text , this type of scoping is sometimes also called lexical scoping. Static scope is standard in modern functional languages such as ML and Haskell because it allows the programmer to reason as if variable bindings are carried out by substitution. Static scoping also makes it much easier to make modular code and reason about it, since its binding structure can be understood in isolation. In contrast, dynamic scope forces the programmer to anticipate all possible dynamic contexts in which the module’s code may be invoked.
它的意思是,某个变量到底是什么值,是由program text决定的,说白了,你写code的时候定义变量的位置在哪儿就哪儿。我举个例子说明一下:
package {
import
flash.display
.Sprite
;
public
class
scope_test extends
Sprite
{
public
function
scope_test(
)
{
(
)
(
)
;
}
private
var
i:int
= 1
;
private
function
fee(
)
:Function
{
var
i:int
= 2
;
var
f:Function
= function
(
)
:void
{
trace
(
i)
// output 2
}
return
f;
}
}
}
fee
这个例子中,函数f在构造函数中执行,但是输出的i不是指向类变量i,而是函数fee里局部变量i。这就是静态作用域的结果,完全是根据文本位置决定的,而不管函数在哪里调用(哪怕在别的对象里)。