'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!



Solution 1:[1]

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);
}

Original answer from 2014:

What you've literally asked for is impossible without using eval unless you want the function to be global. If you do, you can do this:

// Creates global function
window[functionName] = function() { };

Note that that function won't actually have a name (in call stacks and such; but that's changing, see note below), but you can use the name in the variable to call it. So for example:

var functionName = "foo";
window[functionName] = function() {
    console.log("I got called");
};
foo(); // Outputs "I got called"

That's just a specific case of the more general purpose concept of using an object property. Here's a non-global function attached to an object property:

var functionName = "foo";
var obj = {};                       // The object
obj[functionName] = function() { }; // The function

obj[functionName] = function() {
    console.log("I got called");
};
obj.foo(); // Outputs "I got called"

In both cases, it works because in JavaScript, you can refer to a property either using dotted notation and a literal property name (obj.foo), or using bracketed notation and a string property name (obj["foo"]). In the latter case, of course, you can use any expression that evaluates to a string.


Just for completeness, here's how you'd do it with eval:

(function() { // This scoping function is just to emphasize we're not at global scope
  var functionName = "foo";
  eval("function " + functionName + "() { print('I got called'); }");
  foo();
})();

Here's the "note below" about function names: As of the current standard, ECMAScript 5th edition, this function has no name:

var f = function() { };

That's an anonymous function definition. Here's another one:

obj.f = function() { };

In the first, the variable has a name (f), but the function doesn't; in the second, the property on the object has a name, but the function doesn't.

However, that's changing. As of the 6th edition specification (currently still draft), the engine will give the function the name f, even with the expressions above. And it will infer names from slightly more complex expressions as well. Firefox's engine has already done at least some of it for a while, Chrome is starting to, and it'll be specified in the next edition of the spec.

Solution 2:[2]

"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');
}

Solution 3:[3]

Node.js Object Based Dynamic Function Name with Execution

This syntax is somewhat similar to MongoDB / Mongoose Schema Virtuals. You provide the object with a method name and an execution context.

File: temp-obj.js

const modelInstance = {
  name: null,
  virtual(name = null) {
    if (!name) {
      throw new Error("Name is required");
    }
    this.name = name;
    // allows us to chain methods
    return this;
  },
  get(func = false) {
    if (!this.name || !func instanceof Function) {
      throw new Error("Name and function are required");
    }
    // Here we attach the dynamic function name to the "this" Object (which represents the current object modelInstance)
    this[this.name] = func;
    this.name = null;
  },
};
module.exports = modelInstance;

File: index.js

const modelInstance = require("./temp-obj.js");
// This is a two step approach, we name a function and provide it with an execution context
modelInstance.virtual("setMyCount").get((count) => {
  return { count: count };
});

const objVal = modelInstance.setMyCount(100);
console.log(objVal);

If interested, I have a similar response using a JavaScript Class Based Dynamic Function Name

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ethan Brown
Solution 3 Jason