"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can You Create Runtime-Named Functions in JavaScript Without `eval`?

Can You Create Runtime-Named Functions in JavaScript Without `eval`?

Published on 2024-11-15
Browse:806

Can You Create Runtime-Named Functions in JavaScript Without `eval`?

Runtime-Named Functions without Eval in JavaScript

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.

ES6 Solution: Computed Property Names

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.

Function Name Visibility

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.

Latest tutorial More>

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