gdt
gdt

Reputation: 1903

JavaScript - string containing the name of a function

Normally, if I had a string containing the name of a function, I could do something like ...

window[functionName](arguments);

However, that doesn't work when using "jQuery object" style programming (or whatever the correct term is). For example;

(function ($) {
    "use strict";
    $.test = (function () {
        var func1 = function () {
            alert("func1");
        };

        var func2 = function () {
            alert("func2");
        };

        return {
            Test: function (functionName) {
                var fn = window[functionName]; // Need to specify scope here, somehow
                if (typeof fn === 'function') {
                    fn();
                } else {
                    alert("fn() = " + fn);
                }
            }
        }

    } ());
} (jQuery));

$.test.Test("func1");
$.test.Test("func2");

Ideally this would display func1 followed by func2 - but clearly the scoping is wrong, and I'm not sure how to indicate it in this case.

How can I specify the scope of the function that I'm trying to call in this case? I could of course use eval(), but I'm trying to avoid that ...

Thanks.

Upvotes: 1

Views: 54

Answers (1)

Andy E
Andy E

Reputation: 344793

Use an object map to house the functions instead:

    var funcs = {
        func1: function () {
            alert("func1");
        },
        func2: function () {
            alert("func2");
        }
    };

    return {
        Test: function (functionName) {
            var fn = funcs[functionName];
            if (typeof fn === 'function') {
                fn();
            } else {
                alert("fn() = " + fn);
            }
        }
    };

Upvotes: 4

Related Questions