2011-07-04 21 views
1

這AS3功能適用於常規方法和getter方法:如何調用帶有參數的setter方法動態閃光AS3

public function MyClassTestAPI(functionName:String, ...rest):* { 
    var value:*;    
     try { 
      switch(rest.length) { 
       case 0: 
        value = myObj[functionName]; 
        break; 
       case 1: 
        value = myObj[functionName].call(functionName, rest[0]); 
        break; 
       case 2: 
        value = myObj[functionName].call(functionName, rest[0],rest[1]); 
        break; 
       default: 
        throw("Cannot pass more than 2 parameters (passed " + rest.length + ")"); 
      }     
     } 
     return value;     
    } 

使用範例:

this.MyClassTestAPI("Foo", "arg1"); // tests function Foo(arg1:String):String 
this.MyClassTestAPI("MyProperty"); // tests function get MyProperty():String 
this.MyClassTestAPI("MyProperty", "new value");// tests function set MyProperty(val:String):void 

第三個電話不工作(拋出異常)。 我怎樣才能使它適用於setter方法? 謝謝!

編輯:
這是一個可以工作的版本,除了帶有附加參數的getter和setter。 這是確定適合我的需要:

public function MyClassTestAPI(functionName:String, ...rest):* { 
    var value:*;    
     try { 
      if (typeof(this.mediaPlayer[functionName]) == 'function') { 
       switch(rest.length) { 
       case 0: 
        value = myObj[functionName].call(functionName); 
        break; 
       case 1: 
        value = myObj[functionName].call(functionName, rest[0]); 
        break; 
       case 2: 
        value = myObj[functionName].call(functionName, rest[0],rest[1]); 
        break; 
       default: 
        throw("Cannot pass more than 2 parameters (passed " + rest.length + ")"); 
       }     
      } else { 
       switch(rest.length) { 
       case 0: 
        value = myObj[functionName]; 
        break; 
       case 1: 
        myObj[functionName] = rest[0]; 
        break; 
       default: 
        throw("Cannot pass parameter to getter or more than one parameter to setter (passed " + rest.length + ")"); 
       }     
      } 
     } 
     return value;     
    } 

回答

1

二傳手功能可以作爲變量,所以你不能以這種方式來使用它:

myProperty.call("new value"); 

您的變量函數是沒有意義的,因爲你只需要做一個值分配:

myProperty = "new value"; 

通過,你可以將其包含在你的函數有兩種方式方式:

  1. 創建第三個參數是什麼告訴你的函數是一個函數或變量
  2. 創建閉鎖段
+0

這是錯誤的正確原因賦值,雖然我一直試圖做一個檢測二傳手與功能,甚至使用嘗試...捕捉編譯器會對代碼中的兩種方法感到不安。 – shanethehat

+0

這可能會幫助你: flash.utils.describeType(objectWhichOwnsThePropertyOrFunction) 它給出了一個XML,它包含了對象的所有公共屬性和方法。 –

+0

我接受了你的答案,但用typeof來猜測它是否是getter/setter。我在問題中添加了一個解決方案。謝謝!我會發布另一個關於取消交換機的問題。 – Gil