explorers' club

explorations in dev, science, sci-fi, games, and other fun stuff!

variable instantiation via anonymous functions

Leave a comment

[Note to Self]

rather than:

var foo:Object = function ():Object
{
   var o:Object = {};
   o.id = "foo";
   o.data = Math.random();

   return o;
}; //will fail with a CTE cannot coerce function to object

you need only add this:

var foo:Object = function ():Object { .... }(); //will succeed :)

What’s going on here? Well the first will fail giving you a CTE (compile-time error) stating that you are implicitly coercing a function to an object.  And that’s true, you have in no way actually called the anonymous function in the first example.  Rather you have DECLARED it.

The second bit of code is still declaring/defining the function however you are immediately calling said function afterward.

Not necessarily a best practice but a good trick to add to your bag o’ tricks.  Thanks to Nicola Bortignon (http://www.nicolabortignon.com/) for showing me this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s