The this keyword in inline functions
by Ruben
I just spent about half an hour trying to figure out why the inline function I used as a parameter for callLater wasn't being executed properly (not even when I tried setTimeout instead).
After this short timespan of mental agony someone pointed out to me that I had to leave out the this keyword of my inline function. And I thought most scope-related problems would have fled with the arrival of Actionscript3.0...
So for the sake of clarity, this is wrong:
callLater (function():void{ this.myVar = "bla-die-bla"; });
..and this is right:
callLater (function():void{ myVar = "bla-die-bla"; });
..well that is unless you intend to execute from within the global scope.
Comments (show one trackback)
Trackbacks:
What is really going on is that when you use ‘this’ within an inline function you have to think of what context or class the function is executed in at runtime. In the exanoke of a close handler for an Alert the close handler is called from an AlertForm so ‘this’ refers to the AlertForm class.
A quick fix might be something like:
var outerThis:Object = this;
callLater (function():void{
outerThis.myVar = “bla-die-bla”;
});
[...] In line functions in ActionScript and this(link) [...]