Reputation: 2137
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?
Upvotes: 1
Views: 76
Reputation: 39456
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.
Upvotes: 1