Click here to close now.


Adobe Flex Authors: Matthew Lobas, Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex

Adobe Flex: Article

Closures in ActionScript 3

Should you use closures in Object-Oriented programming?

From Farata Systems blog

Closures play a cornerstone role for dynamic languages. They are essential for implementing features like OO or building frameworks. At the same time, a formal definition of closures does not really help to understand them. Let us go through few examples. First, we’ll show what closures look like, and then we’ll give you their use patterns.
It all starts with the use of an anonymous function that has access to variables in the outer lexical scope:
<?xml version=”1.0″?>
<mx:Application xmlns:mx=””
   layout=”vertical” creationComplete=”doInit(event)”>
import mx.controls.Alert;
private var greeting:String=”Hello”;
private function doInit(evt:Event) : void {
  btn.addEventListener(”click”, function(evt:Event):void { greeting + “, ” + txt.text);
<mx:Button id=”btn” label=”closure” />
<mx:TextInput id=”txt”/>
Compile and run this code - it shows the message box.
Here’s an oversimplified three-part description of closures:
1.Closures are functions which are defined in one class or function context and passed to another object for execution at a later time.
2.Closure’s “attachment” happens at run-time ( and can be executed multiple times during application run). It is just the stack-frame allocation where all context variables (“greeting” in our case) are being saved for later use. In most cases it is about surrounding variables of the hosting function and current run-time class instance.
3.Finally, closure’s execution can happen at any time, and can also have parameters at the time of call. A standard convention is to have an “Event” object being passed in with the information from the calling object.
It seems you can use closures to “snapshot” any number of parameters. Unfortunately, it is true for some dynamic languages, but not for ECMA Script ones – ActionScript and JavaScript. Let us illustrate the difference with few examples. First, let us make sure that ActionScript closures are compile-time artifacts rather then true dynamic interpreted counterparts. First, let us swap the order of closure and greetings definition statements.
<?xml version=”1.0″?>
<mx:Application xmlns:mx=””
   layout=”vertical” creationComplete=”doInit(event)”>
import mx.controls.Alert;
private var myClosure :Function = function(evt:Event) { greeting + “, ” + txt.text);
private function doInit(evt:Event) : void {
  btn.addEventListener(”click”, myClosure);
private var greeting:String=”Hello”;
<mx:Button id=”btn” label=”closure”/>
<mx:TextInput id=”txt”/>
It still works, even though “greeting” should have been undefined at the time of closure definition – proving that just reference is being used. Also, unlike in Java, the scope of an object is the stack-frame content of the enclosing function or a class. Here is example that would not compile in Java, but is perfectly legal in AS3:
private function aaa():void{
    { var a = 1; } //in Java a is not visible outside of the block;
 Flash is a stack machine, a closure is a stack variable in the enclosing function, and this stack-frame approach greatly simplifies implementation of closures and code optimizers based on stack, even though requires some adjustments in the coding style. Another issue is that we do not have object values here – everything is done by reference. Let us replace greeting’s value right before the call:
<mx:Button label="closure" click="greeting=’good morning’"/>
As you can see, the greeting was replaced on alert screen with the new value – would not happen if “closure” would use greeting reference by value in the time of definition.
Closures are first class citizens of  ActionScript. Every method in your class is a closure. That is how it knows instance variables of the class. Essentially every class is a big closure. You can write a function with closures inside that would be very much a class for all practical purposes.
Closures are unavoidable when you use asynchronous operations or need to process an event on the other object. Almost any non-trivial action in Flex – communication with the server or getting an input from user – is asynchronous. Using closure automatically gives you the reference to the class instance in which you have your function to the external object processing the event. That is sufficient for processing the asynchronous method’s results in most cases. Automatic pointing of “this” context to the instance defining the function greatly simplifies the coding as it is natural to the developer.
Prior to Flex 2, in Flex 1.5 developers were responsible for supplying context to the closure. Ability to replace closure context gives greater flexibility to the code making it truly dynamic.
The next code sample shows a closure on an arbitrary object to provide a custom context object:
public class Closure extends Object {
   public static function create(context:Object, func:Function, … pms):Function {
   var f:Function = function():*
    var target:*  =;
    var func:*    = arguments.callee.func;
    var params:*  = arguments.callee.params;
    var len:Number = arguments.length;
    var args:Array = new Array(len);
    for(var i:Number=0; i  <len;i++)
           args[i] = arguments[i];

    args["push"].apply(args, params);
    return func.apply(target, args);
   var _f:Object = f;  = context;
   _f.func    = func;
   _f.params  = pms;
   return f;
The following code illustrates how to call this closure:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=”” layout=”absolute” creationComplete=”onCreationComplete(event)”>
  import mx.controls.Alert;
  private var myClosure:Function ;
  private function onCreationComplete (evt:Event):void {
   myClosure = Closure.create({greeting:”Good evening”},function(name:String):void { this.greeting + “, ” + name);
   var greeting:String;
   greeting =”Hello”;
<mx:Button id=”btn” label=”closure” />
Now, the alert shows “Good evening, world” because the method has been applied using different context. Often this methodology is called “delegation” and used by business frameworks to centralize processing of certain events.
The above example illustrates the relationship between context, functions and closures. Using this technique allows you to implement dynamic inheritance, polymorphism and other OO concepts.

More Stories By Anatole Tartakovsky

Anatole Tartakovsky is a Managing Principal of Farata Systems. He's responsible for creation of frameworks and reusable components. Anatole authored number of books and articles on AJAX, XML, Internet and client-server technologies. He holds an MS in mathematics. You can reach him at [email protected]

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
Container technology is shaping the future of DevOps and it’s also changing the way organizations think about application development. With the rise of mobile applications in the enterprise, businesses are abandoning year-long development cycles and embracing technologies that enable rapid development and continuous deployment of apps. In his session at DevOps Summit, Kurt Collins, Developer Evangelist at, examined how Docker has evolved into a highly effective tool for application delivery by allowing increasingly popular Mobile Backend-as-a-Service (mBaaS) platforms to quickly crea...
Cloud computing delivers on-demand resources that provide businesses with flexibility and cost-savings. The challenge in moving workloads to the cloud has been the cost and complexity of ensuring the initial and ongoing security and regulatory (PCI, HIPAA, FFIEC) compliance across private and public clouds. Manual security compliance is slow, prone to human error, and represents over 50% of the cost of managing cloud applications. Determining how to automate cloud security compliance is critical to maintaining positive ROI. Raxak Protect is an automated security compliance SaaS platform and ma...
The cloud. Like a comic book superhero, there seems to be no problem it can’t fix or cost it can’t slash. Yet making the transition is not always easy and production environments are still largely on premise. Taking some practical and sensible steps to reduce risk can also help provide a basis for a successful cloud transition. A plethora of surveys from the likes of IDG and Gartner show that more than 70 percent of enterprises have deployed at least one or more cloud application or workload. Yet a closer inspection at the data reveals less than half of these cloud projects involve production...
Internet of @ThingsExpo, taking place June 7-9, 2016 at Javits Center, New York City and Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 18th International @CloudExpo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world and ThingsExpo New York Call for Papers is now open.
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York and Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound cha...
We are rapidly moving to a brave new world of interconnected smart homes, cars, offices and factories known as the Internet of Things (IoT). Sensors and monitoring devices will touch every part of our lives. Let's take a closer look at the Internet of Things. The Internet of Things is a worldwide network of objects and devices connected to the Internet. They are electronics, sensors, software and more. These objects connect to the Internet and can be controlled remotely via apps and programs. Because they can be accessed via the Internet, these devices create a tremendous opportunity to inte...
Today air travel is a minefield of delays, hassles and customer disappointment. Airlines struggle to revitalize the experience. GE and M2Mi will demonstrate practical examples of how IoT solutions are helping airlines bring back personalization, reduce trip time and improve reliability. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Dr. Sarah Cooper, M2Mi’s VP Business Development and Engineering, explored the IoT cloud-based platform technologies driving this change including privacy controls, data transparency and integration of real time context with p...
We all know that data growth is exploding and storage budgets are shrinking. Instead of showing you charts on about how much data there is, in his General Session at 17th Cloud Expo, Scott Cleland, Senior Director of Product Marketing at HGST, showed how to capture all of your data in one place. After you have your data under control, you can then analyze it in one place, saving time and resources.
The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
Just over a week ago I received a long and loud sustained applause for a presentation I delivered at this year’s Cloud Expo in Santa Clara. I was extremely pleased with the turnout and had some very good conversations with many of the attendees. Over the next few days I had many more meaningful conversations and was not only happy with the results but also learned a few new things. Here is everything I learned in those three days distilled into three short points.
DevOps is about increasing efficiency, but nothing is more inefficient than building the same application twice. However, this is a routine occurrence with enterprise applications that need both a rich desktop web interface and strong mobile support. With recent technological advances from Isomorphic Software and others, rich desktop and tuned mobile experiences can now be created with a single codebase – without compromising functionality, performance or usability. In his session at DevOps Summit, Charles Kendrick, CTO and Chief Architect at Isomorphic Software, demonstrated examples of com...
As organizations realize the scope of the Internet of Things, gaining key insights from Big Data, through the use of advanced analytics, becomes crucial. However, IoT also creates the need for petabyte scale storage of data from millions of devices. A new type of Storage is required which seamlessly integrates robust data analytics with massive scale. These storage systems will act as “smart systems” provide in-place analytics that speed discovery and enable businesses to quickly derive meaningful and actionable insights. In his session at @ThingsExpo, Paul Turner, Chief Marketing Officer at...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
In his General Session at 17th Cloud Expo, Bruce Swann, Senior Product Marketing Manager for Adobe Campaign, explored the key ingredients of cross-channel marketing in a digital world. Learn how the Adobe Marketing Cloud can help marketers embrace opportunities for personalized, relevant and real-time customer engagement across offline (direct mail, point of sale, call center) and digital (email, website, SMS, mobile apps, social networks, connected objects).
The Internet of Everything is re-shaping technology trends–moving away from “request/response” architecture to an “always-on” Streaming Web where data is in constant motion and secure, reliable communication is an absolute necessity. As more and more THINGS go online, the challenges that developers will need to address will only increase exponentially. In his session at @ThingsExpo, Todd Greene, Founder & CEO of PubNub, exploreed the current state of IoT connectivity and review key trends and technology requirements that will drive the Internet of Things from hype to reality.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessions, I wanted to share some of my observations on emerging trends. As cyber security serves as a fou...
Continuous processes around the development and deployment of applications are both impacted by -- and a benefit to -- the Internet of Things trend. To help better understand the relationship between DevOps and a plethora of new end-devices and data please welcome Gary Gruver, consultant, author and a former IT executive who has led many large-scale IT transformation projects, and John Jeremiah, Technology Evangelist at Hewlett Packard Enterprise (HPE), on Twitter at @j_jeremiah. The discussion is moderated by me, Dana Gardner, Principal Analyst at Interarbor Solutions.
Too often with compelling new technologies market participants become overly enamored with that attractiveness of the technology and neglect underlying business drivers. This tendency, what some call the “newest shiny object syndrome” is understandable given that virtually all of us are heavily engaged in technology. But it is also mistaken. Without concrete business cases driving its deployment, IoT, like many other technologies before it, will fade into obscurity.
With all the incredible momentum behind the Internet of Things (IoT) industry, it is easy to forget that not a single CEO wakes up and wonders if “my IoT is broken.” What they wonder is if they are making the right decisions to do all they can to increase revenue, decrease costs, and improve customer experience – effectively the same challenges they have always had in growing their business. The exciting thing about the IoT industry is now these decisions can be better, faster, and smarter. Now all corporate assets – people, objects, and spaces – can share information about themselves and thei...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound effect on the world, and what should we expect to see over the next couple of years.