开发者

ActionScript – Default Datatype for Untyped Variables?

if i don't specifically type a variable in my code will it compile as a default datatype? for example, the "for each ... in" function works best without typing the variable:

for each (var element in myArray)
         {
         //process each element
         }

does my element variable have a datatype? if it is typed as Object is it better to actually write element:Object or does it matter?

EDIT

actually, that was a bad example, since the eleme开发者_StackOverflow中文版nt variable is going to be typed to whatever element is in myArray.

but is that how it works if a variable is untyped? it will simply become what is passed to it?

here's a better example for my question:

var a = "i'm a string"; //does this var becomes a String?

var b = 50.98; //does this var becomes a Number?

var c = 2; //does this var becomes an int?


for each (var element in myArray)

The element variable doesn't have any data type - it is untyped and thus can hold anything.

And yeah, it is equivalent to writing element:Object or element:*, but it is always advisable to type your variables - this will help you catch some errors before you run the code. The mxmlc compiler will emit a warning if you don't do this, which can be fixed by typing it as e:Object or e:*.


var a = 45.3;  //untyped variable `a`
a = "asd";     //can hold anything

/*
    This is fine:  currently variable `a` contains 
    a String object, which does have a `charAt` function.
*/
trace(a.charAt(1));

a = 23;
/*
    Run time error: currently variable `a` contains 
    a Number, which doesn't have a `charAt` function.
    If you had specified the type of variable `a` when 
    you declared it, this would have been 
    detected at the time of compilation itself.
*/
trace(a.charAt(1)); //run time error


var b:Number = 45.3; 
b = "asd"; //compiler error
trace(a.charAt(1)); //compiler error
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜