Create a JavaScript function dynamically from a string name

前端 未结 4 1940
一个人的身影
一个人的身影 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: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.

提交回复
热议问题