A Few days ago I was worried by a to my mind strange behaviour cause by anonymous event handlers:
I would have thought that this code…
private var myVar:int=5;
public function MainClass()
{
trace("MainClass: this: " + this +" - " + getQualifiedClassName(this));
addEventListener(FlexEvent.INITIALIZE, test);
}
public function test(e:Event = null):void
{
trace("test: this: " + this +" - " + getQualifiedClassName(this));
var c:Button = new Button();
c.addEventListener(FlexEvent.INITIALIZE, function(evt:Event):void
{
trace("FlexEvent.INITIALIZE: this: " + this +" - " + getQualifiedClassName(this));
});
c.addEventListener(MouseEvent.CLICK, function(evt:Event):void
{
trace("MouseEvent.CLICK: this: " + this +" - " + getQualifiedClassName(this));
trace("this.myVar: "+this.myVar);
trace("myVar: "+myVar);
});
addChild(c);
}
would produce this output…
MainClass: this: Main0 - Main test: this: Main0 - Main MouseEvent.CLICK: this: Main0 - Main this.myVar: 5 myVar: 5
instead it produced this output:
MainClass: this: Main0 - Main test: this: Main0 - Main MouseEvent.CLICK: this: [object global] - global this.myVar: undefined myVar: 5
This was quite strange to me but the really interesting part was without the ‘this’ keyword I was able to access my class variables!
The reason for this issue is (as far as I understand), that anonymous functions are attached to global so their this is global. Why are class-variables accessible without this? Because of the scope.
I hope this saves you from struggling around with ‘this’ not being ‘this’
warappa
Advertisement