AS3: Function.apply

by troy on January 3, 2008

When using method closures, it sometimes it helps to have some default arguments, and later some optional arguments to pass. This example will look at passing additional params when using Elastic tweens.

Using Function.apply it's pretty easy to concat the arguments into one argument list. Though it should be noted that it's significantly slower than just passing them, which is appropriate if the number of arguments is of a known quantity.

////// parameters for our tween, some of these will change over time //////
var t:String = 0; //current time
var b:String = 0; //begin val
var c:String = 1; //change val
var d:String = 1; //duration
 
var _fA:Array = [1, 2]; //parameters for elastic tweening
 
function _f(a:Object, b:Object, c:Object, d:Object, e:Object = null, f:Object = null, g:Object  = null ):Object {
trace("a:" + a + " b:" + b + " c:" + c + " d:" + d + " e:" + e + " f:" + f + " g:" + g);
return a + b + c;
}
 
//note that the first value is null, as when using a method closure,
//the scope the function is being evaluated in is fixed to that of the class.
 
var calc = _f.apply(null,[t,b,c,d].concat(_fA));
 
trace("result " + calc);

A faster way is to avoid array manipulations, and just route based on the number of arguments. e.g. arg1, arg2 are

var calc
 if(numOfArgs==4){
       calc = _f.apply(null,[t,b,c,d]);
  } else if (numOfArgs == 6){
      calc = _f.apply(null,[t,b,c,d,arg1,arg2]) ;
  } else if (numOfArgs == 8){
      calc = _f.apply(null,[t,b,c,d,arg1,arg2,arg3,arg4]) ;
  }

//a:t b:b c:c d:d e:1 f:2 g:null
//result tbc

{ 0 comments… add one now }

Leave a Comment

 

{ 2 trackbacks }

Previous post:

Next post: