Grow your CSS skills. Land your dream job.

Function name as variable?

  • # September 30, 2012 at 10:20 pm

    Is it possible to use a variable as a function name?

    For example:


    var string = "my_function";
    string();

    When I try to use that, I get an error that string is not a function, but there is a function named as that?

    # September 30, 2012 at 10:47 pm

    Why wouldn’t you just call `my_function()`?

    What you can do is this:

    var newVariable = function () {
    // your stuff
    });
    newVariable();

    # September 30, 2012 at 10:52 pm

    I have to make it dynamic because I’m calling it from a click and checking some things before deciding which function to call. For example I’m checking screen size and then calling functions based on that as well as another value. The two put together make up the existing function name.

    __
    # September 30, 2012 at 11:05 pm

    function my_function(){ /* do stuff */ }
    var str = ‘my_function';
    window[str](); /* does stuff */

    works in Chrome. didn’t test elsewhere.

    # October 1, 2012 at 1:00 pm

    Thanks @traq! So far, my testing has been successful in a few browsers!

    # October 1, 2012 at 1:12 pm

    Couldn’t you use a Switch statement to determine which to call?

    var string = “my_function”;
    switch(string)
    {
    case “function_1″:
    function_1();
    break;
    case “function_2″:
    function_2();
    break;
    default:
    function_default();
    }

    Then, if you wanted to add another possibility, all you really have to do is add a case.

    # October 1, 2012 at 2:05 pm

    I was thinking of using a switch statement but that would bloat the code and I was really hoping for less code to manage and hopefully a smaller file size. Looks like the method @traq suggested seems to be the better option.

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".