A.as :
public class A {
public function getFunction():Function {
return function():void {
if(this is C) {
trace("C");
} else {
trace("not C");
}
}
}
public function func1():void {
var internalFunc:Function = getFunction();
internalFunc();
}
}
B.as :
public class B extends A implements C {
}
In some other class :
var b:B = new B();
B.func1();
Output is :
“Not C”
I was expecting the trace output to be
“C”
Can someone explain why?
An anonymous function, if called directly, is scoped to the global object. If you trace
thisinside it, you will see[object global]instead of[object B], as you would, if this refered tob.A common workaround is using a closure:
Please note however, the instance-members of a class defining an anonymous function are available from within. This works, because they are resolved at compile time.
edit in response to Amarghosh’s question:
Yes,
thispoints to the global object, but that doesn’t mean, you cannot access the instance members of the declaring class. This little piece of code should explain the details:greetz
back2dos