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
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");