gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:39:13 24 4
gpt4 key购买 nike

我有一个对象 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()方法。它与 call 类似,但您将参数作为 Array 传递。像这样的东西:

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, 1.0, 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 ()

关于flash - 如何在Flash AS3中动态调用参数数量未知的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6592705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com