Fact of life with ECMAScript (hence, with ActionScript as well).

Take a look at the language specification itself for details, but locals in 
your example are scoped to the function, not to code blocks within the function 
delimited by braces. Yes, this differs from C-based languages, and as someone 
who regularly works in both I've been bitten by this more than once as well.

Best,
Seth

From: [email protected] [mailto:[EMAIL PROTECTED] On Behalf Of 
toofah_gm
Sent: Thursday, December 04, 2008 2:32 PM
To: [email protected]
Subject: [flexcoders] Method variable scoping problem with Flex compiler

I came across another scoping issue today that scared me. I sure wish
that the scoping in the ActionScript language worked the same way C++,
C#, Java, and others work!

Here's the code:

for each (var o:Object in myArray)
{
var myProblemObject:ProblemObject;
if (some condition)
{
myProblemObject = new ProblemObject();
... more code here ...
}
... still more code here...

if (myProblemObject)
{
... do some stuff ...
}
}

In this code myProblemObject is NULL when things start out...great!
The problem comes after an instance of myProblemObject gets created.
Every time through the loop after this myProblemObject is no longer
NULL. This is not consistent with any other language that I have
worked with and is therefore not obvious to the developer working with
the code.

Why is myProblemObject not reset each time through the loop? It is a
variable declaration.

Gary

--- In [email protected], "toofah_gm" <[EMAIL PROTECTED]> wrote:
>
> It seems to me and my co-workers that the Flex compiler is broken
when
> it comes to local variable scoping within methods.
>
> For example:
>
> for (var i:int=0; i<count; i++)
> {
> // do something
> }
>
> for (var i:int=0; i<count; i++)
> {
> // do something else
> }
>
> This gives a compiler warning stating that 'i' is already defined.
> But in every other language that I have used, this is completely
> valid. Yes 'i' was defined above, but 'i' should only be scoped
> within the 'for' loop and should be invalid outside of it.
>
>
>
> Another example:
>
> if (x)
> {
> var myArray:Array = new Array();
> // do more stuff
> }
>
> myArray.push("some data");
>
> This one compiles, when I believe that it shouldn't. myArray should
> only be defined within the 'if' statement. If you don't go into the
> 'if' statement you have a problem here.
>
>
> Does anyone understand why the Flex compiler allows this? Is this
> just a BUG with the compiler?
>
> Anyway, this is just driving me a little crazy. ;)
>
> Gary
>

Reply via email to