Is it possible to use a variable as a function name

I have a context menu that returns the menu item clicked as a value in a variable, like so.

var m = key;

The variable can be anything I program, for example; edit, cut, paste or anything else I want.

  • popup window at chrome extensions' context menu
  • Custom Context Menu with Javascript?
  • How to re-enable the context menu in this case?
  • Is there a close event for the browser contextmenu
  • 2 jQuery.contextMenu on a page with different trigger
  • Override site specific JavaScript right click context menu with browser specific right click context menu
  • Is it possible to use this variable as a function name?
    For example: function m() where m can be the content of the variable.

    Any suggestions will be much appreciated.

    Thanks

    Chris

  • CKEditor 3.6.3 Enable browser spellcheck and disable context menu
  • How do I trigger the browser context menu on an element. (As if the user right-clicked)
  • popup window at chrome extensions' context menu
  • How to add a custom right-click menu to a webpage?
  • Can we disable right clicking on Anchor Tag in HTML
  • Is there a close event for the browser contextmenu
  • 3 Solutions collect form web for “Is it possible to use a variable as a function name”

    Another way

    function my_generic_function(m) {
        switch (m) {
        case "cut":
            console.log("cutting");
            break;
        case "copy":
            console.log("copying");
            break;
        default:
            return false;
    
        }
    }
    
    var m = "cut";
    my_generic_function(m);
    
    var m = "copy";
    my_generic_function(m);
    ‚Äč
    

    You could create an object with the functions you need and then use the variable to call the functions:

    var funcs = {
       "cut": function(){
          console.log("Cutting");
        },
        "paste": function(){
          console.log("Pasting");
        }
    };
    
    var m = "cut";
    funcs[m]();
    

    http://jsfiddle.net/WVBNV/

    Sure can!

    var onComplete = fadeOut;
    
    function fadeOut(){
       $(this).animate({
          opacity: "0"
       },400);
    }
    

    Coincidentally, you can also use this a way to pseudo make classes.

    function myClass(){
        this.publicVar = "" //<-- this is a public var
        var privateVar = ""; //<-- this is private
    
       this.myPublicMethod = myPublicMethod;
    
       function myPublicMethod(){ // <-- public because of the line above
    
       } 
    
       function _myPrivateMethod(){ // <-- if just this it's private
    
       }
    
    }