Create a JavaScript function dynamically from a string name

前端 未结 4 1941
一个人的身影
一个人的身影 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;
    
    0 讨论(0)
  • 2020-12-11 16:43

    In case you don't want to create new functions based on some string, but based on another similar function: (this might not be a good example but hope you can get the idea)

    function createListOfFunctions(functionNameList) {
      resultFunctions = {};
    
      // Loop all names to create a list of functions with those names
      $.each(functionNameList, function(index, functionName) {
        resultFunctions[functionName] = _createFunction(functionName);
      });
    
      return resultFunctions;
    }
    
    function _createFunction(name) {
      return function(anotherNameToCompare) {
        // customize this funciton whatever you like
        return name == anotherNameToCompare;
      };
    }
    
    
    // USAGE:
    functionNameList = ['stack', 'overflow'];
    result = createListOfFunctions(functionNameList); // result = { stack: function(name) {...}, overflow: function(name) {...} }
    
    result.stack('stack'); // true
    result.stack('not stack'); // false
    result.overflow('overflow'); // true
    
    0 讨论(0)
  • 2020-12-11 16:50
    function registerFunction(functionBody) {
             "use strict";
             var script = document.createElement("script");
             script.innerHTML = "function " + functionBody;
             document.body.appendChild(script);
    }
    registerFunction("fooBar(x, y) { return x + y; }");
    fooBar(1, 2); // will give you 3
    

    Although this is essentially the same as eval() but it will register the function in the domain of the current page. You can later remove this script element, or reuse it for other functions.

    0 讨论(0)
  • 2020-12-11 16:59

    Try this:

    var classname = "myFunction";
    
    window[ classname ] = function () {};
    
    alert( window[ classname ] ); // => undefined
    
    0 讨论(0)
提交回复
热议问题