You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用字符串作为名称定义全局函数?

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 into creator.
  • The assigned function is a simple one that returns 0 whenever it's called, just as you requested.
  • globalThis is the modern, standard way to reference the global scope across different environments (browsers use window, Node.js uses global, and globalThis works 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:23:20