Creating Functions with Runtime-Determined Names (Without Eval)
In JavaScript, creating functions with runtime-determined names is feasible in ECMAScript 2015 and later, utilizing two key features: anonymous function expressions and computed property names.
ES2015 Solution:
In ES2015, anonymous function expressions assigned to object properties inherit the name of that property. This enables us to:
const dynamicName = "foo" + Math.floor(Math.random() * 1000); const obj = { [dynamicName]() { throw new Error(); }, }; const f = obj[dynamicName]; // Demonstrate function's name property console.log("Function's `name` property: " + f.name); // Exception handling reveals the name in stack traces try { f(); } catch (e) { console.log(e.stack); }
In this code:
Compatibility Note:
Note that while all modern browsers implement the functionality, Edge and Safari do not display the assigned name in stack traces.
The above is the detailed content of How to Create Functions with Runtime-Determined Names in JavaScript (Without Eval)?. For more information, please follow other related articles on the PHP Chinese website!