Guest User

Untitled

a guest
May 8th, 2012
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment