Screenwriter, Choreographer, Game Developer

Different types of weak references

Posted on

Actionscript 3 seems to have two different types of weak references. The difference relates to method closures (or bound methods) and the weak references used by the EventDispatcher and Dictionary classes. Try the following

   import flash.display.*;
   import flash.utils.Dictionary;
   public class Test extends Sprite
      private var dic:Dictionary;
      private var store:Function;
      public function Test() {
         var listen:Sprite = new Sprite(); 0xFF0000 ); 50, 50, 50 );
         addChild( listen );

         dic = new Dictionary( true );
         dic[inDictionary] = 1;
         dic[inDictionaryAndProperty] = 1;
         store = inDictionaryAndProperty;
         listen.addEventListener( MouseEvent.CLICK, doClick );
         listen.addEventListener( MouseEvent.CLICK, 
                             inEventListeners, false, 0, true );
      public function doClick( ev:MouseEvent ):void {
         for( var fn:Object in dic ) {
            fn( ev );

      public function inDictionary( ev:MouseEvent ):void {
         trace( "method in dictionary" );

      public function inDictionaryAndProperty( ev:MouseEvent ):void {
         trace( "method in dictionary and property" );
      public function inEventListeners( ev:MouseEvent ):void {
         trace( "method in event listeners" );

The output is

method in dictionary and property
method in event listeners

The EventDispatcher retains the weak reference to the method closure (inEventListeners) because the object it's bound to still exists. It will drop its reference to the method closure when the bound object no longer exists.

The Dictionary, however, doesn't retain the weak reference to the method closure (inDictionary), despite the fact that the method still exists (it exists in the class) and the object it is bound to still exists.

If, however, you have another, strong, reference to the same method closure (inDictionaryAndProperty), then it isn't garbage collected and the Dictionary retains its reference to it.

So the EventDispatcher and Dictionary treat weak references to method closures differently.

It seems to me that the Dictionary takes a purist view - it holds the only reference to the method closure so it can be garbage collected - while the EventDispatcher takes a practical view - the method and the bound object both exist so the method closure should be retained.

Why the difference? I'd love to know.

Share this post or a comment online -

Also in the collection Actionscript