2009-07-14 105 views
0

我有函数回调的数组,像这样:如何使用函数指针指向对象实例的方法?

class Blah { 
    private var callbacks : Array; 

    private var local : Number; 

    public function Blah() { 
     local = 42; 

     callbacks = [f1, f2, f3]; 
    } 

    public function doIt() : Void { 
     callbacks[0](); 
    } 

    private function f1() : Void { 
     trace("local=" + local); 
    } 

    private function f2() : Void {} 
    private function f3() : Void {} 

} 

如果我运行这段代码,我得到 “当地=未定义”,而不是 “LOCAL = 42”:

blah = new Blah(); 
blah.doIt(); 

所以, Flash函数指针不带上下文。解决这个问题的最好方法是什么?

回答

1

尝试:

callbacks[0].apply(this, arguments array)

callbacks[0].call(this, comma-separated arguments)

如果你想 “扛语境” 尝试:

public function doIt() : Void { 
    var f1() : function(): Void { 
     trace("local=" + local); 
    } 

    f1(); 
} 

这对this.local创建一个封闭的人口会d

1

最简单的方法是使用Delegate类...它使用Vlagged描述的技术工作...虽然我必须修改,我根本不理解代码(它在语法上也是不正确的)。 ..

否则,试试这个:

class AutoBind { 
    /** 
    * shortcut for multiple bindings 
    * @param theClass 
    * @param methods 
    * @return 
    */ 
    public static function methods(theClass:Function, methods:Array):Boolean { 
     var ret:Boolean = true; 
     for (var i:Number = 0; i < methods.length; i++) { 
      ret = ret && AutoBind.method(theClass, methods[i]); 
     } 
     return ret; 
    } 
    /** 
    * will cause that the method of name methodName is automatically bound to the owning instances of type theClass. returns success of the operation 
    * @param theClass 
    * @param methodName 
    * @return 
    */ 
    public static function method(theClass:Function, methodName:String):Boolean { 
     var old:Function = theClass.prototype[methodName]; 
     if (old == undefined) return false; 
     theClass.prototype.addProperty(methodName, function():Function { 
      var self:Object = this; 
      var f:Function = function() { 
       old.apply(self, arguments); 
      } 
      this[methodName] = f; 
      return f; 
     }, null); 
     return true; 
    } 
} 

,并添加本作中布拉赫的最后声明:

private static var __init = AutoBind.methods(Blah, "f1,f2,f3".split(",")); 

是会做的伎俩。 ..请注意,调用F1,F2和F3会越来越慢,虽然,因为他们需要一个额外的函数调用...

格尔茨

back2dos

+0

感谢,但这个似乎有点矫枉过正 – andrewrk 2009-07-14 14:01:49