【问题标题】:Dynamic variable names in static function静态函数中的动态变量名
【发布时间】:2011-12-14 22:08:59
【问题描述】:

考虑到您不能在动态函数中使用“this”,有什么方法可以在静态函数中包含动态变量。

我想做什么:

public static function convertToDynamicString(pString:String):String
{
    if(pString == "" || pString == null) return "";
    var re:RegExp = /(\{\w+\})/;
    var results:Array = pString.split(re);
    var dynamicString:String = "";
    for each(var pWord:String in results)
    {
        if(pWord.substr(0, 1) == "{") dynamicString += this[pWord.substring(1, (pWord.length - 1))];    
        else dynamicString += pWord;
    }
    return dynamicString;
}

问题:

this["variable name"] 在静态函数中不起作用

【问题讨论】:

  • 'this' 意味着你已经创建了你的类的一个实例,当你执行 yourClass.convertToDynamicString() 时不会发生这种情况。

标签: flash actionscript-3 apache-flex flex4 flex4.5


【解决方案1】:

不确定您希望“this”引用什么,但假设您有一个名为“Foo”的类包含您的静态函数,只需使用 Foo[str];

或者,创建一个静态本地对象:

private static var _this:Object = {//your dynamic stuff}

然后使用“_this”。

【讨论】:

    【解决方案2】:

    您可以将实例所需的所有内容(作为参数)传递给静态函数。换句话说,实例可以看到和引用静态,但静态函数不能看到或引用特定的实例。

    【讨论】:

      【解决方案3】:

      如果需要引用静态类的属性,可以使用
      静态类名.staticProperty

      public static class MyClass{
         public static myProperty:*
      
         ....
      
         public static function someFunction():void{
             MyClass.myProperty 
             }
      
         }
      

      如果您想从静态类中引用实例,则无法(如您所说)使用 this 关键字。无论如何,有一个解决办法。您可以声明一个 instance 参数并将实例传递给静态方法

      代码如下:

      public static class Myclass{
          public static function myFunc(parm1:*,param2:*,instance:[type of the istance or generic *]):void{
      
         ....now you can use instance.property!!!!  
         }  
      }
      

      然后你可以这样称呼它

       MyClass.myFunc('foo','bar',this)
      

      希望对您有所帮助。
      再见!
      卢克

      【讨论】:

        猜你喜欢
        • 2010-10-13
        • 1970-01-01
        • 1970-01-01
        • 2016-08-30
        • 1970-01-01
        • 1970-01-01
        • 2014-10-10
        • 1970-01-01
        • 2012-07-22
        相关资源
        最近更新 更多