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

前端 未结 3 1856
不思量自难忘°
不思量自难忘° 2021-02-05 13:32

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          


        
相关标签:
3条回答
  • 2021-02-05 14:22

    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)
    
    0 讨论(0)
  • 2021-02-05 14:27
    instance1[functionName]();

    Check this for some details.

    0 讨论(0)
  • 2021-02-05 14:28

    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.

    0 讨论(0)
提交回复
热议问题