1

There is a way to add functions and properties to via 'prototype' property of every class. However those new functions will only be available in this class instances. Question: Is it possible to add static functions and properties to Object in runtime?

1
  • did you try using "dynamic classes" ? Commented Jan 28, 2014 at 0:53

1 Answer 1

1

No, that is not possible. Static methods are part of a class definition and need to exist at compile-time. If you need to add functions at runtime that are statically callable, you can do so easily enough with an approach like this:

public class StaticMethods
{
    private static var _map:Object = {};

    public static function add(name:String, method:Function):void
    {
        _map[name] = method;
    }

    public static function call(name:String, ...args):*
    {
        if(_map[name])
        {
            return _map[name].apply(StaticMethods, args);
        }
    }
}

With its usage being like so:

function sum(a:int, b:int):int
{
    return a + b;
}


StaticMethods.add("sum", sum);

trace(StaticMethods.call("sum", 5, 10)); // 15

I wouldn't advise this capability though; it will lead to code that is very difficult to debug and maintain.

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

1 Comment

Yeah, you can achieve this by Singleton Pattern. Although I think static vars or function may fit for utils.

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.