如何在此样式的闭包(内部函数)中访问实例变量:this['varName']
?
public class Test extends Sprite
{
private var a0:String = 'a0';
private var a1:String = 'a1';
private var a2:String = 'a2';
public function Test()
{
var testFun:Function = function(evt:Event):void
{
for(var i:uint = 0; i < 3; i += 1)
{
trace(this['a'+i]);//how to access instance variables?
}
};
this.addEventListener(Event.ENTER_FRAME, testFun);
}
}
答案 0 :(得分:2)
方括号可用于访问Object
(所有内容)的属性,与您上面完全相同:
object[propertyName]
或设置属性,假设您的班级是dynamic
或已经拥有您尝试设置的属性:
object[propertyName] = 10;
使用Object,您实际上可以使用for(String in Object)
循环输出所需的所有属性:
var object:Object = {
test: "string",
another: 5
};
for(var i:String in object)
{
trace(i + ": " + object[i]);
}
至于您当前的代码,重组它:
public class Test extends Sprite
{
private var a0:String = 'a0';
private var a1:String = 'a1';
private var a2:String = 'a2';
public function Test()
{
testFun();
}
public function testFun():void
{
for(var i:uint = 0; i < 3; i += 1)
{
trace(this['a'+i]);
}
}
}
如果必须保留内部函数,请将对Test
当前实例的引用解析为:
var testFun:Function = function(subject:Test):void
{
for(var i:uint = 0; i < 3; i += 1)
{
trace(subject['a'+i]);//how to access instance variables?
}
};
然后:
testFun(this);