加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在flash AS3中使用未知数量的参数动态调用方法?

发布时间:2020-12-15 07:30:10 所属栏目:百科 来源:网络整理
导读:我有一个对象MyTester,它有另一个类MyClass的实例, 我想通过它测试MyClass API: public class MyTester { internal var myObj:MyClass; public function MyTester() { this.myObj = new MyClass(); trace(this.MyClassTestAPI("Foo","arg1",arg2)); // test
我有一个对象MyTester,它有另一个类MyClass的实例,
我想通过它测试MyClass API:

public class MyTester {
   internal var myObj:MyClass;

   public function MyTester() {
        this.myObj  = new MyClass(); 

        trace(this.MyClassTestAPI("Foo","arg1",arg2)); // tests function Foo(arg1:String,arg2:Number):String
        trace(this.MyClassTestAPI("MyProperty"));  // tests function get MyProperty():String
        trace(this.MyClassTestAPI("MyProperty","new value"));// tests function set MyProperty(val:String):void
   }

   public function MyClassTestAPI(functionName:String,...rest):* {
        var value:*;            
        try {
            if (typeof(this.mediaPlayer[functionName]) == 'function') {
                switch(rest.length) {
                    case 0:
                        value = myObj[functionName].call(functionName);
                        break;
                    case 1:
                        value = myObj[functionName].call(functionName,rest[0]);
                        break;
                    case 2:
                        value = myObj[functionName].call(functionName,rest[0],rest[1]);
                        break;
                    default:
                        throw("Cannot pass more than 2 parameters (passed " + rest.length + ")");
                }                
            }  else {
                switch(rest.length) {
                    case 0:
                        value = myObj[functionName];
                        break;
                    case 1:
                        myObj[functionName] = rest[0];
                        break;
                    default:
                        throw("Cannot pass parameter to getter or more than one parameter to setter (passed " + rest.length + ")");
               }                
            }
        } 
        return value;                
    }
}

如何取消开关并使其适用于任意数量的参数?
谢谢!

解决方法

使用Function.apply()方法.它与调用相同,但您将参数作为数组传递.就像是:

function doCall( callback:Function,... args ):void
{
    // args is now an array
    callback.apply( null,args );
}


// call it like this
this.doCall( this._myFunc1,1.0 );
this.doCall( this._myFunc2,1.0,2.0 );
this.doCall( this._myFunc3,2.0,"hello" );

// to call these functions
private function _myFunc1( num:Number ):void {}
private function _myFunc2( num:Number,num2:Number ):void {}
private function _myFunc3( num:Number,num2:Number,msg:String ):void {}

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Function.html#apply()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读