Dynamic function names in JavaScript

Creating a function with a custom name is not something you can do easily out of the box in ECMAScript. Thankfully, ECMAScript comes with a custom function constructor.

First, the basic code, which will give most of you want you want:

The above will create an anonymous function, which when called creates the named function (using the name variable). This functionality is a good substitute for when you can’t use eval() but you need a function with a custom name. Eval is generally useless in ES5 strict mode for a number of good reasons, so its best avoided.

However, an issue with the code above is that we had to write the main code into a string. This sucks because it makes it difficult to debug (i.e., we can’t easily set break points), so we want to avoid that as much as possible. The solution is to make the main function external, pass it as an argument to the Function constructor to call it.

Another advantage here is that we can set private variables inside our custom function, which can then be mixed with public arguments. Check this out!:

You can basically the start doing cool things from there, like:

The above is mega useful for dynamically implementing custom DOM-like interfaces… like shims. Enjoy! :)

4 thoughts on “Dynamic function names in JavaScript

  1. Actually this is as bad as eval. The code inside the string is not compiled, because javascript engine have no way to know how will the function look like, so every time you call it it will be parsed again, and again, and again. It hits the performance really bad.

    • I agree. It’s certainly not ideal – but it’s a pretty special case. The use case is that it’s ever called once.

    • I know this is over a year old, but I came across it while looking for a good way to fix a problem we’re having.

      Theoretically you could put the return into a cache and any time after the first you’d call the cache instead. So you’d take a minor hit on the first instantiation but then never again.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>