I am building HTML5 applications at Sencha. It is a great platform, take a look...

 

  Ted Patrick - Developer Relations @ Sencha


   Note: This is the personal blog of Ted Patrick. The opinions and statements voiced here are my own.



Simple Method Closure in AS3

DIGG IT!     Published Friday, January 15, 2010 at 3:23 PM .

Method closures allow you to bind variables into the scope of an anonymous function. Watch the value of local variable 'i' in the example below in the returned anonymous function. It is a bit twisted but results show the scope of local variable 'i' is bound in the returned function from newCounter.

CODE AT PASTIE

package
{
import flash.display.Sprite;

public class ClosureAS3 extends Sprite
{
public function ClosureAS3()
{
init() //giv-em-the-jit :)
}

public function init():void
{
//create a counter
var counter1:Function = newCounter();
trace( counter1() ); //1
trace( counter1() ); //2
trace( counter1() ); //3
var counter2:Function = newCounter();
trace( counter2() ); //1
trace( counter2() ); //2
trace( counter1() ); //4 --> scope of i is still with counter1...cool! :)
}

public function newCounter():Function
{
var i:int = 0; //variable i gets bound into returned anonymous function via method Closure
return function():int
{
//i is available to the scope of the anonymous function
i=i+1;
return i;
}
}
}
}

Scary, functional AS3. :)

Cheers,

Ted :)


Where to find me:

Ted on Twitter - @__ted__
Ted on Adobe Groups
Ted on LinkedIn
Ted on Facebook
Ted at Adobe

Latest

Lists

Links

Jobs

city, state, zip

Archives