Sunday, December 2, 2012

Function closures

A function closure is an object that contains a snapshot of a function and its lexical environment. A function’s lexical environment includes all the variables, properties, methods, and objects in the function’s scope chain, along with their values. Function closures are created any time a function is executed apart from an object or a class. The fact that function closures retain the scope in which they were defined creates interesting results when a function is passed as an argument or a return value into a different scope.

For example, the following code creates two functions: foo(), which returns a nested function named rectArea() that calculates the area of a rectangle, and bar(), which calls foo() and stores the returned function closure in a variable named myProduct. Even though the bar() function defines its own local variable x (with a value of 2), when the function closure myProduct() is called, it retains the variable x (with a value of 40) defined in function foo(). The bar() function therefore returns the value 160 instead of 8.
function foo():Function
     {
          var x:int = 40;
          function rectArea(y:int):int // function closure defined
     {
          return x * y
     }
          return rectArea;
     }
         function bar():void
    {
         var x:int = 2;
         var y:int = 4;
         var myProduct:Function = foo();
        trace(myProduct(4)); // function closure called
     }
       bar(); // 160
Methods behave similarly in that they also retain information about the lexical environment in which they were created. This characteristic is most noticeable when a method is extracted from its instance, which creates a bound method. The main difference between a function closure and a bound method is that the value of the this keyword in a bound method always refers to the instance to which it was originally attached, whereas in a function closure the value of the this keyword can change. For more information, see “Bound methods”.
Programming Actionscript 3. Powered by Blogger.