开发者

Understanding OOP in Actionscript

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(开发者_JAVA技巧);
   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 this inside it, you will see [object global] instead of [object B], as you would, if this refered to b.

A common workaround is using a closure:

  var self:A = this;
  return function():void {
    if(self is C) {
      trace("C");
    } else {
      trace("not C");
    }
 }

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, this points 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:

package  {
 import flash.display.Sprite;
 public class Test extends Sprite {
  private var foo:String = "foo";
  public function Test() {
   var anonymous:Function = function ():void {
    trace(foo);//foo
    trace(this.foo);//undefined
   };
   anonymous();
  } 
 }
}

greetz
back2dos


A few things with the code that I assume are just typos?

The getFunction() method doesn't return anything and will thus cause a compiler error.
Your call code calls func1() as a static method, not as a method on an instance of the B. This will also cause a compiler error. I believe these are typos.

In my tests, using your modified code. The output is C. There must be something else going on with your code. Here are my mods to A:

    public function getFunction():Function { 
        if(this is C) {
            trace("C");
        } else {
            trace("not C");
        }
        return getFunction;
    }

Here is my mod to the runnable code, which I put in creationComplete of an empty MXML Application file:

            var b:B = new B();
            b.func1();

I assume your "real world" code is more extensive than the sample and there must be something else going on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜