Is there any non-eval way to create a function with a runtime-determined name?

前端 未结 2 2029
灰色年华
灰色年华 2020-11-22 16:53

Is there any way to create a function with a real name that\'s determined at runtime without using eval, and using only pure JavaScript? (So, n

2条回答
  •  时光取名叫无心
    2020-11-22 17:11

    Here's a utility function I came up with some time ago. It uses the Function constructor technique as outlined in @T.J.Crowder's great answer, but improves on its disadvantages and allows fine-grained control over the scope of the new function.

    function NamedFunction(name, args, body, scope, values) {
        if (typeof args == "string")
            values = scope, scope = body, body = args, args = [];
        if (!Array.isArray(scope) || !Array.isArray(values)) {
            if (typeof scope == "object") {
                var keys = Object.keys(scope);
                values = keys.map(function(p) { return scope[p]; });
                scope = keys;
            } else {
                values = [];
                scope = [];
            }
        }
        return Function(scope, "function "+name+"("+args.join(", ")+") {\n"+body+"\n}\nreturn "+name+";").apply(null, values);
    };
    

    It allows you being tidy and avoiding complete access to your scope via eval, e.g. in the above scenario:

    var f = NamedFunction("fancyname", ["hi"], "display(hi);", {display:display});
    f.toString(); // "function fancyname(hi) {
                  // display(hi);
                  // }"
    f("Hi");
    

提交回复
热议问题