AS3作用域规则 — 静态作用域

AS3中的作用域规则可能会让人感到混乱,但其实它遵循静态作用域,也称作字面作用域。静态作用域是根据代码的文本位置来确定变量引用,这种规则在现代函数式语言如ML和Haskell中常见。静态作用域允许程序员通过代换理解变量绑定,并简化模块化代码的编写和理解。文章通过实例解释了静态作用域如何工作,即使函数在不同环境中调用,变量的绑定仍基于其在代码中的原始位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。这就是静态作用域的结果,完全是根据文本位置决定的,而不管函数在哪里调用(哪怕在别的对象里)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值