T.J. Crowder T.J. Crowder - 1 month ago 6
Javascript Question

Is there any non-eval way to create a function with a runtime-determined name?

Is there any way to create a function with a real name that's determined at runtime without using

eval
, and using only pure JavaScript? (So, no generated
script
elements, as those are specific to the browser environment [and in many ways would be
eval
in disguise anyway]; no using non-standard features of one particular JavaScript engine, etc.)

Note that I'm specifically not asking about anonymous functions referenced by variables or properties that have names, e.g.:

// NOT this
var name = /* ...come up with the name... */;
var obj = {};
obj[name] = function() { /* ... */ };


There, while the object property has a name, the function does not. Anonymous functions are fine for lots of things, but not what I'm looking for here. I want the function to have a name (e.g., to show up in call stacks in debuggers, etc.).

Answer

The Answer for ECMAScript 2015 (aka "ES6"):

Yes. As of ES2015, the function created by an anonymous function expression assigned to an object property takes the name of that object property. As I write this on 11th May 2015, no JavaScript engine in the wild other than Microsoft's "Project Spartan" for Windows 10 Preview supports this (yes, you read that right, M$ got there before Mozilla or Google), but it is in the spec and implementations will catch up. Update: As of October 2016, recent versions of Chrome implement Function#name and the various rules for assigning names; Firefox still does not, but they'll get there.

So for instance, in ES2015 this creates a function named "foo###" where ### is 1-3 digits:

// SEE COMPATIBILITY NOTE ABOVE, Microsoft Edge or Chrome for now
var dynamicName = "foo" + Math.floor(Math.random() * 1000);
var obj = {
  [dynamicName]() {
    // ...
  }
};
var f = obj[dynamicName];
document.body.insertAdjacentHTML(
  "beforeend",
  "Function name: " + f.name
);

That uses the new ES2015 evaluated property name and new method syntax to create the function and give it a dynamic name, then gets a reference to it in f. (It would also work with [dynamicName]: function() { }, method syntax isn't required, function syntax is fine.)


The Answer for ECMAScript 5 (from 2012):

No. You cannot do that without eval or its cousin the Function constructor. Your choices are:

  1. Live with an anonymous function instead. Modern engines do things to help debugging with those.

  2. Use eval.

  3. Use the Function constructor.

Details:

  1. Live with an anonymous function instead. Many modern engines will show a useful name (e.g., in call stacks and such) if you have a nice, unambiguous var name = function() { ... }; expression (showing the name of the variable), even though technically the function doesn't have a name. In ES6, functions created that way will actually have names if they can be inferred from the context. Either way, though, if you want a truly runtime-defined name (a name coming from a variable), you're pretty much stuck.

  2. Use eval. eval is evil when you can avoid it, but with strings you're in total control of, in a scope you control, with an understanding of the costs (you're firing up a JavaScript parser), to do something you cannot do otherwise (as in this case), it's fine provided you really need to do that thing. But if you're not in control of the string or scope, or you don't want the cost, you'll have to live with an anonymous function.

    Here's how the eval option looks:

    var name = /* ...come up with the name... */;
    var f = eval(
        "(function() {\n" +
        "   function " + name + "() {\n" +
        "       console.log('Hi');\n" +
        "   }\n" +
        "   return " + name + ";\n" +
        "})();"
    );
    

    Live example | Live source

    That creates a function with the name we come up with at runtime without leaking the name into the containing scope (and without triggering the flawed handling of named function expressions in IE8 and earlier), assigning a reference to that function to f. (And it formats the code nicely so single-stepping through it in a debugger is easy.)

    This didn't used to correctly assign the name (surprisingly) in older versions of Firefox. As of the current version of their JavaScript engine in Firefox 29, it does.

    Because that uses eval, the function you create has access to the scope in which it was created, which is important if you're a tidy coder who avoids global symbols. So this works, for instance:

    (function() {
        function display(msg) {
            var p = document.createElement('p');
            p.innerHTML = String(msg);
            document.body.appendChild(p);
        }
    
        var name = /* ...come up with the name... */;
        var f = eval(
            "(function() {\n" +
            "   function " + name + "() {\n" +
            "       display('Hi');\n" +         // <=== Change here to use the
            "   }\n" +                          //      function above
            "   return " + name + ";\n" +
            "})();"
        );
    })();
    
  3. Use the Function constructor, as demonstrated in this article by Marcos Cáceres:

    var f = new Function(
        "return function " + name + "() {\n" +
        "    display('Hi!');\n" +
        "    debugger;\n" +
        "};"
    )();
    

    Live example | Live source

    There we create a temporary anonymous function (the one created via the Function constructor) and call it; that temporary anonymous function creates a named function using a named function expression. That will trigger the flawed handle of named function expressions in IE8 and earlier, but it doesn't matter, because the side-effects of that are limited to the temporary function.

    This is shorter than the eval version, but has an issue: Functions created via the Function constructor do not have access to the scope in which they were created. So the example above using display would fail, because display wouldn't be in-scope for the created function. (Here's an example of it failing. Source). So not an option for tidy coders avoiding global symbols, but useful for those times when you want to disassociate the generated function from the scope in which you're generating it.