Use JavaScript variable as function name?

前端 未结 5 1053
抹茶落季
抹茶落季 2020-12-02 00:23

I have the following code in Javascript:

jQuery(document).ready(function(){
    var actions = new Object();
    var actions;
    actions[0] = \'create\';
            


        
5条回答
  •  半阙折子戏
    2020-12-02 00:35

    Like this:

    actions[key + "Dialog"] = function () { ... };
    

    However, since Javascript functions capture variables by reference, your code will not work as intended.
    You need to define the inner function inside of a separate function so that each one gets a separate key variable (or parameter).

    For example:

    var actionNames = [ 'create', 'update' ];   //This creates an array with two items
    var Dialog = { };    //This creates an empty object
    
    for (var i = 0; i < actionNames.length; i++) {
        Dialog[actionNames[i]] = createAction(actionNames[i]);
    }
    
    function createAction(key) {
        return function() { ... };
    }
    

    You can use it like this:

    Dialog.create(...);
    

    EDIT

    You are trying to pollute the global namespace with multiple dialog-related functions.
    This is a bad idea; it's better to organize your functions into namespace.

    If you really want to polute the global namespace, you can do it like this:

    var actionNames = [ 'create', 'update' ];   //This creates an array with two items
    
    for (var i = 0; i < actionNames.length; i++) {
        this[actionNames[i] + 'Dialog'] = createAction(actionNames[i]);
    }
    

    This will create to global functions called createDialog and updateDialog.
    In a normal function call, the this keyword refers to the global namespace (typically the window object).

提交回复
热议问题