Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 8th, 2012  |  syntax: None  |  size: 0.72 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package
  2. {
  3. import flash.display.Sprite;
  4.  
  5. public class ClosureAS3 extends Sprite
  6. {
  7. public function ClosureAS3()
  8. {
  9. init() //giv-em-the-jit :)
  10. }
  11.  
  12. public function init():void
  13. {
  14. //create a counter
  15. var counter1:Function = newCounter();
  16. trace( counter1() ); //1
  17. trace( counter1() ); //2
  18. trace( counter1() ); //3
  19. var counter2:Function = newCounter();
  20. trace( counter2() ); //1
  21. trace( counter2() ); //2
  22. trace( counter1() ); //4 --> scope of i is still with counter1...cool! :)
  23. }
  24.  
  25. public function newCounter():Function
  26. {
  27. var i:int = 0; //variable i gets bound into returned anonymous function via method Closure
  28. return function():int
  29. {
  30. //i is available to the scope of the anonymous function
  31. i=i+1;
  32. return i;
  33. }
  34. }
  35. }
  36. }