开发者

Passing parameters to a function reference?

开发者 https://www.devze.com 2023-01-11 20:02 出处:网络
I\'m attempting to write a performance testing function that can take any function, run it X times and spit out how long it took that function to run in AS3.I\'ve got it working just fine if a functio

I'm attempting to write a performance testing function that can take any function, run it X times and spit out how long it took that function to run in AS3. I've got it working just fine if a function doesn't take any parameters but it comes up with an error otherwise.

Here's the code:

public static function testFunction(targetFunction : Function, object : Object, ... parameters)
{
    var iterations : int = 10000;
    var i : int = 0;
    var time0 : Number = 0;
    var time1 : Number = 0;

    if (parameters.length == 0)
    {
        time0 = getTimer();

        for (i = 0; i <开发者_JAVA百科; iterations; ++i)
        {
            targetFunction();
        }

        time1 = getTimer();
    }
    else
    {
        time0 = getTimer();

        for (i = 0; i < iterations; ++i)
        {
            targetFunction.call(object, parameters);
        }

        time1 = getTimer();
    }

    trace("Took " + (time1 - time0) + "ms to complete " + iterations + " iterations");
}

This works just fine: testFunction(timelineMethod)

But something like this: testFunction(game.addGameState, game, gameState); // gameState would be the parameters

throws this: TypeError: Error #1034: Type Coercion failed: cannot convert []@2f46491 to g2d.GameState. at Function/http://adobe.com/AS3/2006/builtin::call()

It seems like game or gameState wouldn't be valid instances, but they definitely are. So I'm assuming it doesn't somehow know what object the method to be tested belongs to and its throwing this error.

Any ideas?


function.call requires a list of parameters, the same as if you were to call the function normally.

If you want to pass an array of parameters, you should use function.apply instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消