AS3 动态类动态方法名称
我显然在这里遗漏了一些东西。
我需要从数组中填充动态 AS3 类的方法(请参见下面的愚蠢示例)。
但是当我调用这些方法时,它们看起来都是同一个方法。在下面的示例中,所有方法都是 foobar1
。
如果我手动创建方法,没有循环,一切都很好。
有什么线索吗?
package foo
{
public class Bar
{
public function testDynamicClassSanity():void
{
var foo:Foo = new Foo();
var methods:Object = { foobar1: 101, foobar2: 201, foobar3: 301 };
for (var key:String in methods)
{
var val:Number = methods[key];
foo[key] = function():Number
{
return val;
};
}
// Next trace prints
// 101 = 101 201 = 101 301 = 101
trace(
101, "=", foo.foobar1(),
201, "=", foo.foobar2(),
301, "=", foo.foobar3()
);
}
}
}
internal dynamic class Foo
{
};
I'm clearly missing something here.
I need to fill methods of dynamic AS3 class from an array (see silly example below).
But when I call those methods, all of them appear to be the same method. In the example below, all methods are foobar1
.
If I create methods by hand, without a loop, everything is fine.
Any clues?
package foo
{
public class Bar
{
public function testDynamicClassSanity():void
{
var foo:Foo = new Foo();
var methods:Object = { foobar1: 101, foobar2: 201, foobar3: 301 };
for (var key:String in methods)
{
var val:Number = methods[key];
foo[key] = function():Number
{
return val;
};
}
// Next trace prints
// 101 = 101 201 = 101 301 = 101
trace(
101, "=", foo.foobar1(),
201, "=", foo.foobar2(),
301, "=", foo.foobar3()
);
}
}
}
internal dynamic class Foo
{
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜想问题出在
val
的作用域上——你假设它的作用域是 for 循环,但在 AS3 中情况并非如此,作用域是函数。您的所有呼叫都返回 301,我这样说对吗?更新:由于解决您遇到的问题(变量
val
被引用并且稍后才解决,而不是被“复制”到您的函数中)非常麻烦:根据您的用例,您可以检查该方法调用并使用 代理。I would guess the problem is in the scoping of
val
-- you assume its scope is the for loop, but that is not the case in AS3, the scope is the function. Am I correct that all your calls return 301?Update: As working around the issue that you are experiencing (the variable
val
being referenced and only later resolved instead of being 'copied' into your function) is quite cumbersome: Depending on your use case you could inspect the method calls and just look up the desired result in the table using the functionality provided by Proxy.我认为你的问题是 var 变量的范围。尝试这个修改:(
上面的技巧在 Javascript 中可以解决类似的问题......我打赌它适用于 AS3)
I think that your problem is the scoping of the var variable. Try this modification:
(the above trick works in Javascript to workaround a similar problem... I bet it is applicable to AS3)
作为记录,我将在此处发布
testDynamicClassSanity()
函数的更正版本:For the records, I'll post here the corrected version of the
testDynamicClassSanity()
function: