Create a JavaScript function dynamically from a string name

前端 未结 4 1945
一个人的身影
一个人的身影 2020-12-11 16:11

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

4条回答
  •  被撕碎了的回忆
    2020-12-11 16:37

    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;
    

提交回复
热议问题