ActionScript Variable Scoping and the Lack Thereof
April 28, 2008 – 6:00 amI’ve always disparaged JavaScript (in a bigoted way), and have only learned, and come to use quite often, ActionScript in the past six months. Both are now roughly based on ECMAScript.
I’ve always preferred “real” languages to kludgey script languages. (What is a language? That’ll have to wait for another day.)
The day I stumbled upon the fact that there is no variable scoping in ActionScript reminded me of its lowly origins.
for (var i:int = 0; i<10; i++) {
// do something
}
for (var i:int = 0; i<10; i++) {
// do something else
}
Redeclaring a variable within a method only issues a warning. If you change the type, and error is kicjed out.
Given this language functionality, I have gravitated toward a convention of declaring all variables at the top of the method. Never an inside-the-loop definition.
var i:int;
for (i = 0; i<10; i++) {
// do something
}
for (i = 0; i<10; i++) {
// do something else
}
Here’s a random piece of code. It’s not specifically an example of how you might run afoul with no scoping, but it is an example of using the declaration convention.
private function handle(event:DragEvent):void {
var source:Object = event.dragSource.dataForFormat(dataFormat)[0];
var base:ListBase = event.target as ListBase;
var i:int = base.calculateDropIndex(event);
var currentItem:Object = (i >= base.dataProvider.length) ? null : base.dataProvider[i]; // dragDestination()
if (event.type == DragEvent.DRAG_EXIT || event.type == DragEvent.DRAG_DROP)
currentItem = null;
if (currentItem == lastItem)
return;
var feedback:String = determineFeedback(event);
DragManager.showFeedback(feedback);
if (feedback != DragManager.NONE) {
updateLastItem(currentItem);
setTempValue(currentItem, source);
} else {
updateLastItem(null);
}
base.invalidateList(); // required by lists using labelFunction, they don't catch binding changes
}