Here is the utility function with which I came some time ago. It uses the Function constructor, as pointed out by @TJCrowder, but improves on its shortcomings 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); };
This allows you to be neat and avoid full access to your area with eval , for example. in the above scenario:
var f = NamedFunction("fancyname", ["hi"], "display(hi);", {display:display}); f.toString(); // "function fancyname(hi) { // display(hi); // }" f("Hi");
Bergi Jun 04 '14 at 8:10 2014-06-04 08:10
source share