views:

72

answers:

3

I have heard different things in forums but unable to find a concrete answer on the difference between obj[name] and obj.name. Does the compiler treat them differently?

+5  A: 

Depends if obj is a dynamic class or not. obj[name] is a runtime check for a property where as obj.name would produce a compile-time error if it didn't exist.

mythz
And additionally, it obj['name'] has some obvious use cases that would simply be impossible otherwise (dynamic look ups)
Tyler Egeto
+4  A: 

actually, it's obj[expression] vs. obj.identifier

the former always results in a dynamic runtime lookup, whereas the latter can and will be checked at compile-time. Consequently, it can produce compile-time errors, if obj is sealed (i.e. not dynamic) and doesn't have a property matching the identifier. Also, if the property is not dynamic (i.e. a runtime added property of a dynamic object), but defined in the objects class, then this information is used to perform a faster lookup.

to summarize: in contrast to obj[expression], obj.identifier is type-safe and signifficantly faster

greetz

back2dos

back2dos
+2  A: 
var foobar:String = "id";

var obj:Object = new Object{ id:"the value of variable" };

trace( obj.id ); // the value of variable
trace( obj[ foobar ] ); // value of variable

you would use the [ ] approach if it was a variable and you did not have the name

David Morrow