Is it possible to create a JavaScript function with a name determined at runtime, without using eval or unconventional engine-specific features? Yes, this is now possible with ECMAScript 2015 (ES6) and beyond.
In ES6, an anonymous function expression assigned to an object property takes the name of that property. This can be combined with computed property names to name a function without new Function or eval. For example:
const dynamicName = "foo" Math.floor(Math.random() * 1000); const obj = { [dynamicName]() { throw new Error(); }, }; const f = obj[dynamicName];
This creates a function named "foo###" where ### is a random 1-3 digit number.
The function's name property will reflect the dynamic name. The compatibility note in the code snippet above refers to the fact that Edge and Safari currently do not show the name in stack traces.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3