Home > Article > Web Front-end > Can You Dynamically Name JavaScript Functions Without Using `eval` or Non-Standard Features?
Creating Functions with Dynamic Names in JavaScript
Can one dynamically assign real names to functions without resorting to eval or non-standard JavaScript features? This question arises when seeking functions with identifiable names in debugging contexts.
Solution for ECMAScript 2015 and Later (ES6)
ES2015 introduces a solution. Assigning an anonymous function expression to an object property gives the function the name of that property. This, combined with computed property names, allows function naming without relying on Function constructors or eval.
In ES2015, the following code snippet creates a function with a dynamic name:
const dynamicName = "foo" + Math.floor(Math.random() * 1000); const obj = { [dynamicName]() { throw new Error(); }, }; const f = obj[dynamicName];
The function's name can be retrieved through its name property or observed in error stack traces:
console.log("Function's `name` property: " + f.name + " (see compatibility note)"); try { f(); } catch (e) { console.log(e.stack); }
Note that certain browsers may not display the name in stack traces.
The above is the detailed content of Can You Dynamically Name JavaScript Functions Without Using `eval` or Non-Standard Features?. For more information, please follow other related articles on the PHP Chinese website!