What's the difference between Object, *, and no type at all?

211 views Asked by At

Is there any difference between those three declarations?

var x;
var y:Object;
var z:*;

Is there anything in AS that's not an Object?

4

There are 4 answers

0
Cory Petosky On BEST ANSWER

var x; and var x:*; mean precisely the same thing to the compiler -- the variable can accept any type. Use :* rather than omitting type to enhance readability of your code.

Practically, var x:Object; is equivalent, since as you noted everything descends from Object. However, the compiler treats it different, and it tends to be slightly slower if you're accessing non-Object properties. Additionally, as noted by the other answers, attempting to assign undefined to an Object will automatically cast it to null.

I recommend using :* if your variable can accept more than one unrelated type of value, and using :Object when using an Object as an associative array.

1
Robusto On

In your code, x is not typed, y is typed as the Object class (the foundation class of all ActionScript classes) and z is typed as any type of class. The upshot of this is that anytime you need to reference the public members of those variables, you will either need to cast them as instances of the class you are looking to use or else (in the case of your y Object, but also any other un-typed variables) you will have to test if y.hasOwnProperty("propertyName") before referencing it.

Usually you only see the * in method arguments that can take more than one type of class. For example, you might have an event handler like

private function myHandler(event:*) : void {
  //statements
}

where event can refer to any type of event, and your method's code would determine which type that was before doing anything with it.

0
Patrick On

Everything but undefined is an Object so if you want a var to have the undefined value use the * type.

var a:*=undefined;
trace(a); // will trace undefined

var b:Object=undefined; // you will have a warning at compile time
trace(b); // will trace null
0
Richard Szalay On

The primary difference is that * can be assigned undefined and a namespace, whereas Object cannot. Everything else is fine for both.

I'd recommend using Object where possible as * has some oddness within the AVM.