Function Scopes
/**
* Copyright 9re ( http://wonderfl.net/user/9re )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/mVFY
*/
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
public class NewFunction extends Sprite {
private var messages:Array = [];
private var these:Array = [];
private var myConstructor0:Function = function ():void {
messages.push("\"this\" inside myConstructor: " + this.toString());
these.push(this);
};
private var constructorGenerator:Function = function ():Function {
return function ():void {
messages.push("\"this\" inside constructorGenerator: " + this.toString());
these.push(this);
};
}
public function NewFunction() {
var tf:TextField = new TextField();
tf.defaultTextFormat = new TextFormat("_sans", 12, 0x444444);
tf.width = stage.stageWidth;
tf.height = stage.stageHeight;
addChild(tf);
var myConstructor1:Function = function ():void {
messages.push("\"this\" inside myConstructor: " + this.toString());
these.push(this);
};
myConstructor0();
try {
var myInstance0:Object = new myConstructor0();
} catch(e:Error) {
messages.push("error: " + e.toString());
if (myInstance0 == null)
messages.push("myInstance0 is null");
}
myConstructor1();
var myInstance1:Object = new myConstructor1();
constructorGenerator()();
var myInstance2:Object = new (constructorGenerator());
these.forEach(findThisObject("myInstance1", myInstance1));
these.forEach(findThisObject("myInstance2", myInstance2));
tf.text = messages.join("\n");
}
private function findThisObject($targetName:String, $target:Object):Function {
var found:Boolean = false;
return function($this:Object, $index:int, $array:Array):void {
if ($target && $this && $target == $this) {
messages.push($targetName + " found at index " + $index.toString());
found = true;
} else if (!found && $index + 1 == $array.length)
messages.push($targetName + " not found!");
}
}
}
}