Is Strong Typing Possible with the _global Object?
I recently answered an Adobe forum post in which someone was curious about the _global object in conjunction with strong typing. This person had read a best practices document and wanted to use the post colon syntax introduced with ActionScript 2.0 — :Number, :String, :Object, and the like — but couldn’t figure how to use these suffixes with properties of the _global object (that is, with what people often call “global variables”).
The following, for example, works fine:
_global.myName = "Stilloneous";
… but the compiler generates an error when strong typing is attempted …
_global.myName:String = "Stilloneous";
So what gives? Is this not possible?
Considered verdict
To the best of my understanding and testing, there is only one way to strongly type properties of the _global object, and it happens to be coincidental. The only way — in ActionScript 2.0, at any rate — is to write a custom class with static members (think the Singleton pattern or, say, a static function library). Static classes are not instantiated, otherwise they might be scoped anywhere. In Flash, static classes happen to be stored in the _global object. So there you have it.
But that aside, strong typing is not a possibility for _global properties with “run of the mill,” non-external ActionScript. Post colon syntax seems to be tied closely with the var statement, and var is only used with variables that “stand alone”; that is, with variables defined in the current scope — not defined in terms of another object. This applies with _global, _parent, this, or any other prefix preceding the variable’s name.
For example, if you want to strongly type a variable scoped to a particular movie clip, you must declare it with a var statement in that movie clip’s timeline:
// In a keyframe of a movie clip
var coffee:String = "Turkish";
As opposed to declaring it via object reference from the main timeline, which would not allow strong typing:
// In a keyframe of the main timeline
mcDemitasse.coffee = "Turkish";
Personally, I prefer to keep all my code — outside of the occasional stop() or gotoAndPlay() — in the main timeline. Like many other Flash programmers, I simply “turn the other way” and politely ignore this fact of life when occasion calls for variable declarations without var.
So it really isn’t _global at fault here. There’s nothing special about the _global object, per se, that keeps its properties from being strongly typed. It’s just that _global, like any other prefix, doesn’t (cannot) require var.