Home  >  Article  >  Web Front-end  >  How to Create Functions with Runtime-Determined Names in JavaScript (Without Eval)?

How to Create Functions with Runtime-Determined Names in JavaScript (Without Eval)?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 08:34:01305browse

How to Create Functions with Runtime-Determined Names in JavaScript (Without Eval)?

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:

  • dynamicName determines the function's name dynamically.
  • obj is an object with a property named dynamicName.
  • The anonymous function expression assigned to the dynamicName property indirectly inherits the name.

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!

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