简体   繁体   中英

Dynamically call javascript function based on function arguments

I have a jQuery function which accepts few arguments based on the argument I should call another jQuery function.

example:

arg0 = "Launch"
        arg1 = "menu"

example:

(function($)
 {
    preRender: function(arg0,arg1)
    {
        var nextFuncName = arg0+arg1; //launchmenu
        nextFuncName() // hope to call the function name framed from the number of arguments
     }
})(jQuery);

 (function($)
 {
    launchmenu: function()
     {
       console.log("Launchmenu called");
     }
})(jQuery);

I referred the following link calling a jQuery function named in a variable but I don't want to use eval() or window object.

Is it possible to use $.proxy or any other method to achieve this functionality, also is it possible to achieve this using underscore.js?

Any help will be appreciated.

Try utilizing jQuery object

…or much better an own, local object, instead of polluting the global jQuery namespace.


Merge them so that you use localObject for launchmenu but $ for preRender


 (function($) { var localObject = {}; function launchmenu() { console.log("Launchmenu called") } function preRender(arg0, arg1) { var nextFuncName = arg0 + arg1; if (nextFuncName in localObject) { localObject[nextFuncName]() } else { console.log(typeof nextFuncName) } } localObject.launchmenu = launchmenu; $.preRender = preRender; }(jQuery)); $(function() { $.preRender("launch", "menu"); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>

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