variable instantiation via anonymous functions
[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.
Advertisement
Leave a Comment
wishlist