我们如何动态地调用一个函数。我尝试了以下代码:
public function checkFunc() : void
{
Alert.show("inside function");
}
public var myfunc:String = "checkFunc";
public var newFunc:Function=Function(myfunc);
newFunc();但它带来了错误:
调用可能未定义的方法newFunc。
代替newFunc(),我尝试将其称为this[newFunc](),但这会引发错误:
此关键字不能在静态方法中使用。它只能用于实例方法、函数闭包和全局代码。
在动态调用函数方面有帮助吗?
发布于 2011-06-02 23:16:13
函数的工作方式与属性相同,您可以用分配变量的方式分配它们,这意味着所有时髦的方括号技巧也适用于它们。
public function checkFunc() : void
{
Alert.show("inside function");
}
public var myfunc:String = "checkFunc";
public var newFunc:Function = this[myfunc];
newFunc();发布于 2011-06-02 17:48:30
代码没有经过测试,但应该可以工作。
package {
public class SomeClass{
public function SomeClass( ):void{
}
public function someFunc( val:String ):void{
trace(val);
}
public function someOtherFunc( ):void{
this['someFunc']('this string is passed from inside the class');
}
}
}
// usage
var someClass:SomeClass = new SomeClass( );
someClass['someFunc']('this string is passed as a parameter');
someClass.someOtherFunc();
// mxml example
// Again untested code but, you should be able to cut and paste this example.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="someOtherFunc( )" >
<mx:Script>
<;
}
]]>
</mx:Script>
<mx:Label id="theLabel" />
</mx:Application>发布于 2011-06-02 17:43:49
flash中的函数是对象,与任何对象一样也是这样的函数。AS3 api显示函数有一个call()方法。您的代码非常接近:
// Get your functions
var func : Function = someFunction;
// call() has some parameters to achieve varying types of function calling and params
// I typically have found myself using call( null, args );
func.call( null ); // Calls a function
func.call( null, param1, param2 ); // Calls a function with parametershttps://stackoverflow.com/questions/6216155
复制相似问题