动态调用一个函数

时间:2011-06-02 14:49:45

标签: flex actionscript-3 actionscript flex3

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

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

但它给出了错误:

  

调用可能未定义的方法   newFunc。

代替newFunc(),我尝试将其称为this[newFunc](),但这会引发错误:

  

此关键字无法使用   静态方法。它只能用于   实例方法,函数闭包,   和全球代码

有关动态调用函数的任何帮助吗?

4 个答案:

答案 0 :(得分:5)

函数的工作方式与属性相同,您可以按照分配变量的方式分配它们,这意味着所有时髦的方括号技巧也适用于它们。

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

答案 1 :(得分:3)

taskinoor's answerthis question

instance1[functionName]();
     

查看this了解详细信息。

答案 2 :(得分: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>

答案 3 :(得分:1)

flash中的函数是Objects,就像任何对象一样。 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
相关问题