如何使用字符串作为名称定义全局函数?
Solution to Dynamically Create a Global Function from a String
No problem, here's a straightforward way to implement the creator function you're asking for. This works across both browser and Node.js environments thanks to globalThis, which gives us consistent access to the global scope.
Code Implementation
function creator(funcName) { // Assign the new function to the global scope using the input string as the name globalThis[funcName] = function() { return 0; }; } // Test it out creator('test1'); console.log(test1()); // Outputs: 0
How It Works
- We use bracket notation (
globalThis[funcName]) to dynamically set a property on the global object. Since functions in JavaScript are just objects, this effectively creates a global function with the name passed intocreator. - The assigned function is a simple one that returns
0whenever it's called, just as you requested. globalThisis the modern, standard way to reference the global scope across different environments (browsers usewindow, Node.js usesglobal, andglobalThisworks for both).
Optional: Avoid Overwriting Existing Functions
If you want to prevent accidentally replacing an existing global function, you can add a quick check first:
function creator(funcName) { if (!globalThis[funcName]) { globalThis[funcName] = function() { return 0; }; } else { console.warn(`Function ${funcName} already exists in global scope!`); } }
内容的提问来源于stack exchange,提问作者udayanmaurya
相关产品推荐
相关产品推荐

