首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态调用函数

动态调用函数
EN

Stack Overflow用户
提问于 2011-06-02 14:49:44
回答 3查看 4.1K关注 0票数 2

我们如何动态地调用一个函数。我尝试了以下代码:

代码语言:javascript
复制
public function checkFunc() : void
{
  Alert.show("inside function");
}
public var myfunc:String = "checkFunc";
public var newFunc:Function=Function(myfunc);
newFunc();

但它带来了错误:

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

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

此关键字不能在静态方法中使用。它只能用于实例方法、函数闭包和全局代码。

在动态调用函数方面有帮助吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-06-02 23:16:13

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

代码语言:javascript
复制
public function checkFunc() : void
{
  Alert.show("inside function");
}
public var myfunc:String = "checkFunc";
public var newFunc:Function = this[myfunc];
newFunc();
票数 5
EN

Stack Overflow用户

发布于 2011-06-02 17:48:30

代码没有经过测试,但应该可以工作。

代码语言:javascript
复制
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>
票数 2
EN

Stack Overflow用户

发布于 2011-06-02 17:43:49

flash中的函数是对象,与任何对象一样也是这样的函数。AS3 api显示函数有一个call()方法。您的代码非常接近:

代码语言:javascript
复制
// 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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6216155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档