AS3 variable scopes and shadowing

[code lang="actionscript"]myVar = "some value here";
trace(myVar);
var myVar : String;[/code]

Why on earth does this compile?

It does not only compile, it runs perfectly fine since once compiled all variable declarations are moved to the top of the function. Senocular posted about it long ago.

Something like that simply won't compile in haXe or Android, and I think it's safer.

We recently almost screwed up a demo because of something similar: variable shadowing. In a nutshell, you define two variables with the same name and type in two different scopes. We are used to see this a lot in parameters:

[code lang="actionscript"]function(wadus : String) : void
{
this.wadus = wadus;
}[/code]

And I'm starting to think that maybe we should auto-impose the good old "_" rule to class members:

[code lang="actionscript"]function(wadus : String) : void
{
this._wadus = wadus;
}[/code]

The thing is that if this is not enforced by the compiler, it's quite easy to forget about it.

Also I don't like that you can do things like this:

[code lang="actionscript"]for(var x : int = 0; x < 10; x++)
{
trace("x: " + x);
}

trace("final: " + x);[/code]

That x belongs to the for loop, you shouldn't be allowed to access it outside of it. I don't know, the AS3 scope system always surprises me and most of the times not in a good way :/

Back to index