The following code (from Base64):
                private static const _encodeChars:Vector.<int> = 
InitEncoreChar();  
                private static function InitEncoreChar():Vector.<int>  
                {  
                        var encodeChars:Vector.<int> = new Vector.<int>(64, 
true);  
                        
                        // We could push the number directly  
                        // but I think it's nice to see the characters (with no 
overhead on encode/decode)  
                        var chars:String = 
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  
                        for (var i:int = 0; i < 64; i++)  
                        {  
                                encodeChars[i] = chars.charCodeAt(i);  
                        }  
                        
                        return encodeChars;  
                }  

compiles to:

/**
 * @private
 * @const
 * @type {Array}
 */
com.sociodox.utils.Base64._encodeChars = 
com.sociodox.utils.Base64.InitEncoreChar();

/**
 * @private
 * @return {Array}
 */
com.sociodox.utils.Base64.InitEncoreChar = function() {
  var /** @type {Array} */ encodeChars = new Array(64, true);
  var /** @type {string} */ chars = 
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var /** @type {number} */ i = 0; i < 64; i++) {
    encodeChars[i] = chars.charCodeAt(i);
  }
  return encodeChars;
};

Trying to run this code in javascript will result in an error that 
com.sociodox.utils.Base64.InitEncoreChar is not defined. Of course this makes 
sense based on how the javascript is compiled. (There’s no difference between a 
private static and a public static other than the comments.)

It’s simple enough to fix this by placing functions before variable assignments.

However, the same code works in Flash no matter which order it’s declared. 
That’s probably because the code is analyzed before it’s actually run.

The thing is, that Javascript has the same functionality:

/**
 * @constructor
 */
com.sociodox.utils.Base64 = function() {
        com.sociodox.utils.Base64._encodeChars = InitEncoreChar();
        function InitEncoreChar(){
          var /** @type {Array} */ encodeChars = new Array(64, true);
          var /** @type {string} */ chars = 
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
          for (var /** @type {number} */ i = 0; i < 64; i++) {
            encodeChars[i] = chars.charCodeAt(i);
          }
  return encodeChars;
                
        }
};

This will work no matter which order you declare the variable and the function 
because function declarations are evaluated before code is executed.

I don’t know a way to make this work in JS for public static functions, but for 
private static functions, this is likely a better pattern. It also makes the 
functions truly private…

Of course, I have no idea how much work it would be to make FalconJX be able to 
do this…

Thoughts?

Harbs

Reply via email to