views:

63

answers:

1

I know 'this' differs outside and inside of the closure.
But why numChildren and this.numChildren differs inside the closure?
Or why numChildren is same outside and inside?

var _this:Sprite = this;
trace("[outside]this: " + this);
trace("[outside]numChildren: " + numChildren);
trace("[outside]this.numChildren: " + this.numChildren); 

(function ():void {
    trace("[inside]this: " + this);
    trace("[inside]numChildren: " + numChildren);
    trace("[inside]this.numChildren: " + this.numChildren);
    trace(_this.removeChildAt === removeChildAt);
    trace(this.removeChildAt === removeChildAt);
})();

You can see the code and the output from the following link
How Do You Explain 'this'?

+2  A: 

You can't access the class with the keyword "this" from within a closure. This is why you get that trace result. In your example , the only way to access the class is by using the _this variable. Inside the closure "this" refers to the global object, you're outside the scope of the class.

numChildren is the same outside and inside because it's a property of the class, the same way that if you were tracing the "name" property outside & inside the closure , you would get exactly the same result. in other words , not being able to access the class by using "this", doesn't imply that you can't access its properties.

When you write this.name or this.numChildren , inside the closure , you're not referring to the class anymore, hence the different trace output

PatrickS
Thanks for the detail explanation!
9re