2011-06-02 77 views
2

我们如何动态调用函数。我曾尝试下面的代码:动态调用函数

public function checkFunc() : void 
{ 
    Alert.show("inside function"); 
} 
public var myfunc:String = "checkFunc"; 
public var newFunc:Function=Function(myfunc); 
newFunc(); 

但它给错误:

Call to a possibly undefined method newFunc.

在地方newFunc(),我试着给它this[newFunc](),但抛出的错误:

The this keyword can not be used in static methods. It can only be used in instance methods, function closures, and global code

任何帮助动态调用函数?

+0

可能的复制(http://stackoverflow.com/questions/4489291)的Flex/AS3的 – 2015-01-07 23:41:52

+0

可能重复的 - 调用一个函数动态地使用一个字符串?](http://stackoverflow.com/questions/4489291/flex-as3-calling-a-function-dynamically-using-a-string) – RaYell 2015-01-08 09:08:42

回答

5

功能的工作方式相同属性,你可以给它们分配变量以同样的方式,这意味着所有时髦的方括号技巧也适用于他们。

public function checkFunc() : void 
{ 
    Alert.show("inside function"); 
} 
public var myfunc:String = "checkFunc"; 
public var newFunc:Function = this[myfunc]; 
newFunc(); 
[的Flex/AS3? - 调用一个函数动态地使用字符串]的
3

taskinoor's answerthis question:在闪光

instance1[functionName]();

Check this for some details.

+0

无论在这个链接给出的是我在上面的代码中所做的...但是它给出了错误.. :( – sandy 2011-06-02 18:13:56

+0

@sandy方法包含在静态类中吗? – 2011-06-02 18:37:48

1

函数是对象,并且作为这样的功能,就像任何物体一样。 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 parameters 
+0

默认情况下,对象的第一个参数是函数所属的实例(IE:“this”) – 2011-06-02 17:52:52

+0

oops我的意思是fucntion“call”的第一个参数是 – 2011-06-02 18:04:25

+0

@Ben:I t给出了同样的错误“访问未定义的属性newFunc” – sandy 2011-06-02 18:11:33

2

代码未经测试,但应该工作

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> 
    <![CDATA[ 
     public function someFunc(val:String):void{ 
     trace(val); 
     this.theLabel.text = val 
     } 
     public function someOtherFunc():void{ 

     // this is where call the function using a string 
     this['someFunc']('this string is passed from inside the class'); 
     } 
    ]]> 
    </mx:Script> 

    <mx:Label id="theLabel" /> 
</mx:Application> 
+0

@sandy好了我更新了我的代码给你,一试 – 2011-06-02 20:43:41