

In the test results, both the dynamic Function and the method have a length field. Oddly, Adobe’s documentation does not mention this field. It is, however, mentioned in Mozilla’s documentation for the JavaScript Function class:

length is external to a function, and indicates how many arguments the function expects, i.e. the number of formal parameters. By contrast, arguments.length is local to a function and provides the number of arguments actually passed to the function.

This is a definition for JavaScript, so how does it apply to AS3 which features two additional language features: default parameters and var ars. Are they counted in the length? Let’s check:

	import flash.text.*;
	import flash.display.*;
	public class FunctionLength extends Sprite
		public function FunctionLength()
			var logger:TextField = new TextField();
			logger.autoSize = TextFieldAutoSize.LEFT;
			function log(msg:*): void { logger.appendText(msg+"\n"); }
			log("one: " + one.length);
			log("onePlusOneDefault: " + onePlusOneDefault.length);
			log("onePlusVarArgs: " + onePlusVarArgs.length);
			log("onePlusOneDefaultVarArgs: " + onePlusOneDefaultVarArgs.length);
		private function one(a:int): void {}
		private function onePlusOneDefault(a:int, b:int=0): void {}
		private function onePlusVarArgs(a:int, ...b): void {}
		private function onePlusOneDefaultVarArgs(a:int, b:int=0, ...c): void {}

Note that in this test I am able to simply use the dot (.) operator to access length, even though it is not mentioned in Adobe’s documentation; I did not need to resort to the index operator (["length"]). The documentation is probably just missing the length field and not trying to keep it a secret. Regardless, here is the output of the test program:

Name Required Default Var Args Length
one 1 0 no 1
onePlusOneDefault 1 1 no 2
onePlusVarArgs 1 0 yes 1
onePlusOneDefaultVarArgs 1 1 yes 2

From these results it is clear that regular, required arguments and default arguments are counted in the length field. In contrast, var args are not counted. Since AS2 and JavaScript treat all arguments as optional (arguments not passed are undefined), this may be more useful there. Perhaps an AS3 library like as3signals could make use of the length property to make sure callbacks take enough parameters, but callback with default arguments make this much less useful. Does anyone know of good uses for Function.length? If so, leave a comment below.