Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

class - Create a JavaScript function dynamically from a string name

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...