What's an example of calling a function through a reference (as opposed to directly)?
Asked
Active
Viewed 1,211 times
0
-
1Do you mean like `var functionName:Function = function(arg:*):* {...}` as opposed to `function functionName(arg:*):* {...}`? – Taurayi Feb 05 '11 at 05:22
2 Answers
3
If I understand the question, you want something like this:
function myFunction():void { trace("calling my function!"); }
var functions:Array = [myFunction];
functions[0](); // traces "calling my function!"
The idea being that every function is also an object. When you have myFunction(), if you treat "myFunction" as a variable (note: no ()'s) then you can pass around a reference to that function. This is how, for instance, callbacks work.
For example:
this.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(e:MouseEvent):void {
trace("CLICK!");
}
in your addEventListener call, you're passing a reference to your clickHandler function. Flash then knows that whenever this object receives an event of type MouseEvent.CLICK, it should call the referenced function (in this case, clickHandler).
Does that make sense?

Myk
- 6,205
- 4
- 26
- 33
-
1What's worth noting is that a function reference can actually be stored in a variable typed `Function`, like `var callback:Function = someFunction;` If you want to store arguments/parameters in addition to the function, you can put them in a `var parameters:Array`. You can then later call the function by using the apply() method of a Function object: `callback.apply(null, parameters)`. – epologee Feb 06 '11 at 14:21