且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从字符串名称动态创建JavaScript函数

更新时间:2022-10-15 09:50:09

是:

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

现在,诚实地,这不是正确的但它非常接近。当你通过函数$ c> 表达式来实例化一个函数,并且没有名字时,函数不能引用它自己,除非通过name



如果这很重要,你可以做的是:用一些库内部名称创建函数,然后将它分配给全局名称:

  function secretName(){...} 

window [classname] = secretName;


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.

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;