Create a JavaScript function dynamically from a string name

class, function, javascript

Solution

Yes:

window[classname] = function() { ... };

Now, in honesty, that's not exactly like what you were attempting, but it's pretty close. When you instantiate a function via a `function` expression like that, and without a name, the function can't refer to itself except via the name in the outer scope (in this case, the global scope).

If that's important, what you could do is this: create the function with some stock "internal" name, and then assign it to the global name:

function secretName() { ... }

window[classname] = secretName;

Problem

Given a string `classname`, I want to dynamically create a new JavaScript function named after that string that can be used to instantiate objects. I've tried using `eval()` but for some reason the declared function does not appear in the global (window) scope. ``` eval( "function " + classname + "() {}" ); window[ classname ]; // => undefined ``` Is there a way I can dynamically create a new function named after a string? Or, alternatively, give me some way to reference the created function after creating it via `eval`. Interestingly it appears as a local variable when I debug it in Safari. Update: Got it! Of course it's obvious, I just use `eval` again to create the instance: ``` var myInstance = eval( "new " + classname ); myInstance.constructor.name; // => classname (yay) ``` This should work in my case because I only need to create one instance of the class right after it's declared. For the general case though see Pointy's answer.

Original source