Actionscript: Why is it possible to assign a variable before it is declared?
Asked Answered
A

3

11

inspired by the question int a[] = {1,2,}; Weird comma allowed. Any particular reason? I remembered a question concerning the syntax in Adobe's Actionscript.

For some reason it is possible (at least in Flex 3) to assign a value to a variable before it was declared:

 public function foo() : void {
      a = 3;
      var a : int = 0;
 }

Does this make any sense..? Is this a bug in the Adobe FlexBuilder compiler? Or is this due to maybe some legacy to older Ecmascript editions?

Archibold answered 12/8, 2011 at 19:33 Comment(0)
A
17

An interesting implication of the lack of block-level scope is that you can read or write to a variable before it is declared, as long as it is declared before the function ends. This is because of a technique called hoisting , which means that the compiler moves all variable declarations to the top of the function. For example, the following code compiles even though the initial trace() function for the num variable happens before the num variable is declared...

Actionscript 3.0 Docs - Variables (quote found about 2/3 down the page)

Adam answered 12/8, 2011 at 19:42 Comment(0)
D
3

As far as I know it is the feature of Flash Virtual Machine which declares (allocate memory etc) all the function's variables before function's body execution. So declaring variable somewhere in the function block in ActionScript code just reports compiler to declare variable and it declares at the beginning of the function block at runtime. That's why your code is the same as:

public function foo() : void {
      var a : int = 3;
      a = 0;
 }

The same reason has the compiler warning when you declare some variable twice in the function's body.

Diary answered 12/8, 2011 at 19:39 Comment(2)
Thanks to both of you! Although it sounds a bit weird to me, I finally know the reasonArchibold
@Mister Henson, then you should accept an answer, unless you're waiting for something better :)Precincts
C
0

For further reference: http://wiki.joa-ebert.com/index.php/Local_Variables

Cornall answered 12/8, 2011 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.