1

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.

1
  • 1
    @AndyE's answer is correct, but for your reference, this "jQuery object style" doesn't have an official term, but is an example of a closure (i.e., lexical scope) created using an immediately invoked function expression. Commented Mar 28, 2013 at 11:17

1 Answer 1

4

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);
            }
        }
    };
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks; kind of obvious in hindsight, but I was going down the wrong scoping alley!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.