In actionscript you have only local and "global" scope. Meaning a variable
can be declared as local to the function or in the class that contains it.
Other languages allow for creating further scopes. In Java, C, C++, C#, for
instance, you can do something like this:
int i = 0;
{ // this creates a new scope
int i = 8;
}
And you will get 2 different variables. Obviously, naming both the same is
not the smartest move, but it's legal (at least in C#, if I recall
correctly).
Also when you write a loop, the counter var will be local if declared in the
loop. I mean this:
for(int i = 0; i < 10; i++) {
// do something with i
}
// this is invalid, i doesn not exist here...
i = 20;
Now, in Actionscript this is not possible. You can declare a variable
wherever you like. The compiler ends up moving the variable to the top of
the scope when generating the bytecode (I think this is called hoisting).
So this:
var l:Array = [{},{}]
function test():void{
for each(var i:Object in l){
var id:String;// = null;
trace("1" ,id);
id = "test" + Math.random().toString();
trace("2" ,id);
}
}
Is equivalent to writting this:
var l:Array = [{},{}]
function test():void{
var id:String;// = null;
for each(var i:Object in l){
trace("1" ,id);
id = "test" + Math.random().toString();
trace("2" ,id);
}
}
"id" will be declared (and initialized to null) only once, before you access
it in your code. So you only have one variable, really and that's the reason
for the behavior you observed.
Cheers
Juan Pablo Califano
2010/8/4 Jiri <[email protected]>
> I have the following case:
>
> var l:Array = [{},{}]
> function test():void{
> for each(var i:Object in l){
> var id:String;// = null;
> trace("1" ,id);
> id = "test" + Math.random().toString();
> trace("2" ,id);
> }
> }
>
> I seems that 'id' is not resetted to null on every iteration as I would
> expect. I have to explicitly set the id to null myself! Does some know why
> this is, or are my expectations just wrong.
>
>
> Jiri
> _______________________________________________
> Flashcoders mailing list
> [email protected]
> http://chattyfig.figleaf.com/mailman/listinfo/flashcoders
>
_______________________________________________
Flashcoders mailing list
[email protected]
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders