Dynamic function names in JavaScript

This may seem a bit weird, but can come in handy when creating dynamic event listeners and I'll do my best to explain what I'm trying to achieve.

I have a variable and I want to create a function named after that variable value. Here's en example:

var functionName = "foo";
// Now I want to create a function named foo. foo is a tring

function [functionName](){
   alert('nothing really');
}

foo(); //Should alert "nothing really"

Thanks!

Answers


Updated answer in 2016:

The "However, that's changing..." part of the original answer below has changed. ES2015 ("ES6") was released a year ago, and JavaScript engines are now finally coming into compliance with one of its lesser-known aspects: Function#name.

As of ES2015, this function has a name despite being created using an "anonymous" function expression:

var f = function() { };

Its name is f. This is dictated by the specification (or the new one for ES2016) in dozens of different places (search for where SetFunctionName is used). In this particular case, it's because it gets the name of the variable it's being assigned to. (I've used var there instead of the new let to avoid giving the impression that this is a feature of let. It isn't. But as this is ES2015, I'll use let from now on...)

Now, you may be thinking "That doesn't help me, because the f is hardcoded," but stick with me.

This function also has the name f:

let obj = {
    f: function() { }
};

It gets the name of the property it's being assigned to (f). And that's where another handy feature of ES2015 comes into effect: Computed property names in object initializers. Instead of giving the name f literally, we can use a computed property name:

let functionName = "f";
let obj = {
    [functionName]: function() { }
};

Computed property name syntax evaluates the expression in the [] and then uses the result as the property name. And since the function gets a true name from the property it's being assigned to, voilĂ , we can create a function with a runtime-determined name.

If we don't want the object for anything, we don't need to keep it:

let functionName = "f";
let f = ({
    [functionName]: function() { }
})[functionName];

That creates the object with the function on it, then grabs the function from the object and throws the object away.

Of course, if you want to use lexical this, it could be an arrow function instead:

let functionName = "f";
let f = ({
    [functionName]: () => { }
})[functionName];

Here's an example, which works on Chrome 51 and later but not on many others yet:

// Get the name
let functionName = prompt(
  "What name for the function?",
  "func" + Math.floor(Math.random() * 10000)
);

// Create the function
let f = ({
    [functionName]: function() { }
})[functionName];

// Check the name
if (f.name !== functionName) {
    console.log("This browser's JavaScript engine doesn't fully support ES2015 yet.");
} else {
    console.log("The function's name is: " + f.name);
}

"Global" functions in JavaScript are simply properties on the global context object (window in a browser). So you can do what you're looking for this way:

var functionName = 'foo';

window[functionName] = function() {
    alert('nothing really');
}

Need Your Help