Is There Any Non-Eval Way to Create a Function with a Runtime-Determined Name

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

The Answer for ECMAScript 2015+ (aka "ES6"):

Yes. As of ES2015, the function created by an anonymous function expression assigned to an object property takes the name of that object property. This is implemented in all modern browsers, although Edge and Safari don't use the name in stack traces. We can use that in combination with another ES2015 feature (computed property names) to name a function without new Function or eval.

In ES2015 this creates a function named "foo###" where ### is 1-3 digits:

const dynamicName = "foo" + Math.floor(Math.random() * 1000);const obj = {  [dynamicName]() {    throw new Error();  }};const f = obj[dynamicName];// See its `name` propertyconsole.log("Function's `name` property: " + f.name + " (see compatibility note)");// We can see whether it has a name in stack traces via an exceptiontry {  f();} catch (e) {  console.log(e.stack);}

Dynamic function name in javascript?

As others mentioned, this is not the fastest nor most recommended solution. Marcosc's solution below is the way to go.

You can use eval:

var code = "this.f = function " + instance + "() {...}";
eval(code);

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

The Answer for ECMAScript 2015+ (aka "ES6"):

Yes. As of ES2015, the function created by an anonymous function expression assigned to an object property takes the name of that object property. This is implemented in all modern browsers, although Edge and Safari don't use the name in stack traces. We can use that in combination with another ES2015 feature (computed property names) to name a function without new Function or eval.

In ES2015 this creates a function named "foo###" where ### is 1-3 digits:

const dynamicName = "foo" + Math.floor(Math.random() * 1000);const obj = {  [dynamicName]() {    throw new Error();  }};const f = obj[dynamicName];// See its `name` propertyconsole.log("Function's `name` property: " + f.name + " (see compatibility note)");// We can see whether it has a name in stack traces via an exceptiontry {  f();} catch (e) {  console.log(e.stack);}

Javascript: Dynamic function names

window.example = function () { alert('hello world') }
example();

or

name = 'example';
window[name] = function () { ... }
...

or

window[name] = new Function('alert("hello world")')


Related Topics



Leave a reply



Submit