Drenai
Drenai

Reputation: 12357

Flex/AS3 - calling a function dynamically using a String?

Is it possible to call a function in AS3 using a string value as the function name e.g.

var functionName:String = "getDetails";

var instance1:MyObject = new MyObject();

instance1.functionName(); // I know this is so wrong, but it gets the point accross:)

UPDATE

The answer from @Taskinoor on accessing a function is correct:

instance1[functionName]();

And to access a property we would use:

instance1[propertyName]

Upvotes: 14

Views: 12821

Answers (3)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48630

I have created the following wrappers for calling a function. You can call it by its name or by the actual function. I tried to make these as error-prone as possible.

The following function converts a function name to the corresponding function given the scope.

public static function parseFunc(func:*, scope:Object):Function {
    if (func is String && scope && scope.hasOwnProperty(funcName)) {
        func = scope[func] as Function;
    }
    return func is Function ? func : null;
}

Call

Signature: call(func:*,scope:Object,...args):*

public static function call(func:*, scope:Object, ...args):* {
    func = parseFunc(func, scope);
    if (func) {
        switch (args.length) {
            case 0:
                return func.call(scope);
            case 1:
                return func.call(scope, args[0]);
            case 2:
                return func.call(scope, args[0], args[1]);
            case 3:
                return func.call(scope, args[0], args[1], args[2]);
            // Continue...
        }
    }
    return null;
}

Apply

Signature: apply(func:*,scope:Object,argArray:*=null):*

public static function apply(func:*, scope:Object, argArray:*=null):* {
    func = parseFunc(func, scope);
    return func != null ? func.apply(scope, argArray) : null;
}

Notes

Call

The switch is needed, because both ...args and arguments.slice(2) are Arrays. You need to call Function.call() with variable arguments.

Apply

The built-in function (apply(thisArg:*, argArray:*):*) uses a non-typed argument for the argArray. I am just piggy-backing off of this.

Upvotes: 1

iklubov
iklubov

Reputation: 21

You may use function.apply() or function.call() methods instead in the case when you dont know whether object has such method for instance.

var functionName:String = "getDetails";
var instance1:MyObject = new MyObject();
var function:Function = instance1[functionName]
if (function)
    function.call(instance1, yourArguments)

Upvotes: 2

taskinoor
taskinoor

Reputation: 46037

instance1[functionName]();

Check this for some details.

Upvotes: 23

Related Questions