Home > Article > Web Front-end > Can You Create Dynamically Named Functions in JavaScript Without Using `eval()`?
Dynamic Function Creation Without Eval
Question: Is it possible to create a function with a runtime-determined name without resorting to eval() and using only pure JavaScript?
Answer for ECMAScript 2015 :
Yes, ES2015 introduces a solution. Anonymous function expressions assigned to object properties now inherit the property name as their function name. This can be combined with computed property names, allowing the creation of functions with dynamic names.
Example:
const dynamicName = "foo" + Math.floor(Math.random() * 1000); const obj = { [dynamicName]() { throw new Error(); }, }; const f = obj[dynamicName]; console.log("Function's `name` property: " + f.name); // Logs: "foo###" (where ### is 1-3 digits)
In ES2015, this method ensures that the function has a name and that it appears in stack traces in debuggers. However, note that Edge and Safari may not display the function name in stack traces.
The above is the detailed content of Can You Create Dynamically Named Functions in JavaScript Without Using `eval()`?. For more information, please follow other related articles on the PHP Chinese website!