2009-07-14 73 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

相關問題