2009-02-19 57 views
2

我正在開發一個Flash(Flash 9,AS3)來連接到服務器併發送/接收/解析數據到JavaScript/HTML上的聊天。 我有這樣的結構:原型和靜態類型變量的ActionScript問題

package { 
    public class myClass { 
     String.prototype.escapeHtml = function() { 
      var str = this.replace(/&/g, "&"); 
      str = str.replace(/</g, "&lt;"); 
      str = str.replace(/>/g, "&gt;"); 
      return str; 
     } 

     function writeToBrowser(str:String) { 
      ExternalInterface.call("textWrite",str.escapeHtml()); 
     } 
    } 
} 

當我編譯它,我得到這個錯誤:

1061: Call to a possibly undefined method escapeHtml through a reference with static type String.

如果我刪除:String,這一切工作正常,但後來我不得不檢查str是否是一個字符串,以及它是否未定義等等。

我在我的代碼中有很多像這樣的函數,其中許多函數接收用戶輸入的數據,所以我認爲刪除:String並對每個函數進行多次檢查並不是最好的方法。

我該如何解決這個問題?

回答

2

然後,只需定義功能。

,並稱之爲:

public function writeToBrowser(str : String) 
{ 
    ExternalInterface.call("textWrite", escapeHtml(str)); 
} 

:)

+0

這將解決這個問題,但是當你有函數(function2(function3(str)))時,它只是醜陋而已。可能這是我的錯誤編碼。 – Mauricio 2009-02-19 15:45:53

1

原型實際上是遺留的。在類

public function escapeHtml(str : String) : String 
{ 
    var str = this.replace(/&/g, "&amp;"); 
    str = str.replace(/</g, "&lt;"); 
    str = str.replace(/>/g, "&gt;"); 

    return str; 
} 

你應該繼承String類和使用您的自定義類

package { 
    public class myClass { 

     public function writeToBrowser(str:CustomString) { 
       ExternalInterface.call("textWrite",str.escapeHtml()); 
     } 
    } 
    public class CustomString { 

     public function escapeHtml():String { 
       var str = this.replace(/&/g, "&amp;"); 
       str = str.replace(/</g, "&lt;"); 
       str = str.replace(/>/g, "&gt;"); 
       return str; 
     } 
    } 
} 
+0

謝謝,這工作完美! – Mauricio 2009-02-19 14:42:26

+0

其實,有一個問題。我實際上無法擴展String類(「1016:Base class is final」),所以我放棄了拆分,替換等方法,我需要它們。 – Mauricio 2009-02-19 14:56:01

2

你會得到一個錯誤,因爲編譯器在嚴格模式。 如果你想留在嚴格的模式,你可以試試這個:

ExternalInterface.call("textWrite",str["escapeHtml"]());