Home >Web Front-end >JS Tutorial >Can You Create Dynamically Named Functions in JavaScript Without Using `eval()`?

Can You Create Dynamically Named Functions in JavaScript Without Using `eval()`?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 16:51:03360browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn