2011-06-02 80 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