最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Use JavaScript variable as function name? - Stack Overflow

programmeradmin1浏览0评论

I have the following code in Javascript:

jQuery(document).ready(function(){
    var actions = new Object();
    var actions;
    actions[0] = 'create';
    actions[1] = 'update';
    for (key in actions) {
        // Dialogs
        var actions[key]+Dialog = function(){
            $('#'+actions[key]+'dialog').dialog('destroy');
            $('#'+actions[key]+'dialog').dialog({
                resizable: false,
                height:600,
                width:400,
                modal: true,
                buttons: {
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });
        };
    }
});

I want to create 2 functions in loop(createDialog and updateDialog). How can i do this? In PHP there is very simple $$var. But how make variable variable in JS I don't know.

Thank you

I have the following code in Javascript:

jQuery(document).ready(function(){
    var actions = new Object();
    var actions;
    actions[0] = 'create';
    actions[1] = 'update';
    for (key in actions) {
        // Dialogs
        var actions[key]+Dialog = function(){
            $('#'+actions[key]+'dialog').dialog('destroy');
            $('#'+actions[key]+'dialog').dialog({
                resizable: false,
                height:600,
                width:400,
                modal: true,
                buttons: {
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });
        };
    }
});

I want to create 2 functions in loop(createDialog and updateDialog). How can i do this? In PHP there is very simple $$var. But how make variable variable in JS I don't know.

Thank you

Share Improve this question edited Apr 6, 2012 at 5:28 user166390 asked Sep 1, 2010 at 14:21 Alex PliutauAlex Pliutau 22k28 gold badges114 silver badges144 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 6

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).

You'll need a reference to the scope object in which you want to create the functions. If it's the global scope you can use window:

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

javascript global scope is window, so you can write:

var funcName='varfuncname';
    window[funcName]=function() {
    alert('HI!');
}

Now you can call it as window[funcName]();, window['varfuncname'](); or varfuncname();

You need to combine SLaks' and RoToRa's answers:

var actionNames = [ 'create', 'update' ];   //This creates an array with two items

for (var i = 0; i < actionNames.length; i++) {
    window[ actionNames[i] + 'Dialog' ] = function() {
        $('#'+ actionNames[i] +'dialog').dialog('destroy');
        $('#'+ actionNames[i] +'dialog').dialog({
            resizable: false,
            height:600,
            width:400,
            modal: true,
            buttons: {
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        });
    }
}

Since you're running this in the document ready event handler, the "this" variable would refer to the document, not the window.

I think you're trying to do something that you don't need to do in JavaScript. In PHP, function passing is a bit of a kludge. In JavaScript it is elegant and painless.

How are you planning on calling these functions later? I'm guessing that you have these function names hard-coded into your HTML in the 'onclick' attributes. Hard-coding JavaScript into your HTML via the on* attributes is a bad idea. If that's what you're doing, you have to create variables in the global scope (another practice best avoided). In the browser, the global object is window. If you define a property on window, the function will be available globally:

$(document).ready(function() {
  var myNames = [
    'create',
    'destroy'
  ];
  for (var i = 0; i < myNames.length; i++) {
    window[myNames[i] + 'Dialog'] = function() {
      alert('Hello');
    };
  }
});

This assumes that you have onclick attributes in your HTML that match up with the function names you're creating.

A better way to do this would be to just create the functions as you bind them to the events, never even assigning them to variables:

$(document).ready(function() {
  $('#createdialog, #destroydialog').each(function() {
    $(this).click(function() {
      alert('Hello');
    });
  });
});

This will make both your JavaScript and your HTML smaller and cleaner.

发布评论

评论列表(0)

  1. 暂无评论