Home >Web Front-end >JS Tutorial >Can You Create a Named Function in JavaScript with a Runtime-Determined Name?
Creating Functions with Runtime-Determined Names without eval
Question:
Is it possible to create a named function in pure JavaScript without using eval or non-standard features, where the function name is determined at runtime?
Answer (ES6 only):
Yes, in ES6 and later (aka "ES2015 "), this is possible using anonymous function expressions assigned to computed object property names.
const dynamicName = "foo" + Math.floor(Math.random() * 1000); const obj = { [dynamicName]() { // ... }, }; const f = obj[dynamicName]; console.log("Function's `name` property: " + f.name); // Outputs "foo###", where ### is a random 1-3 digit number
In this example, we use a computed property name to dynamically generate a random name for the function. The function is assigned to the object property, and its name can be accessed via the name property. However, note that browser compatibility may vary, and some browsers may not display the dynamic function name in stack traces.
The above is the detailed content of Can You Create a Named Function in JavaScript with a Runtime-Determined Name?. For more information, please follow other related articles on the PHP Chinese website!