this is global

13 11 2008

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

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.