2

Is there any way that you can have dynamic variables inside of a static function considering that you can't use "this" inside a dynamic function.

What I am trying to do:

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;
}

Problem:

this["variable name"] doesn't work in static functions

1
  • 1
    'this' implies that you've created an instance of your class, which doesn't happen when you do yourClass.convertToDynamicString(). Commented Dec 14, 2011 at 22:27

3 Answers 3

5

Not sure what you want "this" to reference, but assuming you have a class named "Foo" that contains your static function, just use Foo[str];

Alternatively, create a static local object:

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

And then use "_this".

Sign up to request clarification or add additional context in comments.

Comments

0

You can pass everything to your static function that it needs from the instance (as arguments). In other words, the instance can see and reference statics, but static functions can't see or reference a particualr instance.

Comments

0

If you need to refer to a property of the static class you can use
StaticClassName.staticProperty

public static class MyClass{
   public static myProperty:*

   ....

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

   }

If you want to refer to the instance from the static class there's no way (as you said) of using the this keyword. Anyway there's a work around. you can declare an instance parameter and pass the instance to the static method

here's the code:

public static class Myclass{
    public static function myFunc(parm1:*,param2:*,instance:[type of the istance or generic *]):void{

   ....now you can use instance.property!!!!  
   }  
}

and then you can call it this way

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

Hope this can help you.
Bye!
Luke

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.