简体   繁体   中英

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.

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);
            }
        }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM