Keo Strife
Keo Strife

Reputation: 1446

function argument as string but execute as function?

I have a function (named “chal") which simply console.log() the arguments if they are NOT a function or call the function otherwise.

function chal(){
    for(var i = 0, iLen = arguments.length; i<iLen;i++)
        if(typeof arguments[i] == "function")
            //if argument is a function, call it
            arguments[i]();
        else
            //if argument is NOT a function, console.log the value
            console.log(arguments[i]);
}

I have an array (named “arr") which contain a function “AS A STRING”

var arr = [
    "argumentAsString",
    123,
    "function(){console.log('this is a function');}"
];

I need “chal" function to run with arguments from “arr” array but the function as string in the array get called as a function.

I know it's very confusing... here is jsFiddle: http://jsfiddle.net/YqBLm/1/

I know it's wield but I actually ran into a situation when I need to do such thing... I basically passed the function from server-side to client as string (function.toString()) and now i need to pass it as an argument to a function on client-side... Can anyone think of anything?

Thanks a lot in advance!!

Upvotes: 0

Views: 70

Answers (1)

Jordan Foreman
Jordan Foreman

Reputation: 3888

If you encapsulate the function in a module (object), you could call it like so:

JavaScript

var module = {
    argumentAsString: function(){..}
}

var arr = [
    "argumentAsString",
    123,
    "function(){console.log('this is a function');}"
];

function chal(){
    for(var i = 0, iLen = arguments.length; i<iLen;i++)
        if(module.hasOwnProperty[arguments[i]])
            //if argument is a function, call it
            module[arguments[i]]();
        else
            //if argument is NOT a function, console.log the value
            console.log(arguments[i]);
}

EDIT

I may have misinterpreted the question! :p

Try assigning that function to a variable, and storing that variable in the array instead:

var fcn= function(){
    console.log('this is a function');
}

var arr = [
    "argumentAsString",
    123,
    fcn
];

EDIT 2

If I'm right, neither of the above two answers will solve your problem. See this similar question: Convert string (was a function) back to function in Javascript

Upvotes: 2

Related Questions