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

如何替换esbuild生成代码中的Function("return this")以规避Linter警告?

解决Linter对Function构造函数的警告问题

我正在处理一段esbuild生成的代码,代码检查工具(Linter)因为使用Function("return this")()触发了类似eval()风险的警告。相关代码如下:

var require_root = __commonJS({
  "../node_modules/lodash/_root.js"(exports2, module2) {
    var freeGlobal = require_freeGlobal();
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")(); // <========= 此行触发警告
    module2.exports = root;
  }
});

替代方案

Function("return this")()的作用是跨环境获取全局对象,以下几种写法可以替代它,同时避免Linter警告:

  • 优先使用标准全局对象globalThis
    ES2020引入的globalThis是跨环境的标准全局对象,直接用它做兜底:

    var root = freeGlobal || freeSelf || globalThis;
    

    若要兼容极旧环境(不支持globalThis),可以扩展判断逻辑:

    var root = freeGlobal || freeSelf || 
      (typeof globalThis !== 'undefined' ? globalThis : 
       typeof window !== 'undefined' ? window : 
       typeof global !== 'undefined' ? global : 
       typeof this !== 'undefined' ? this : {});
    
  • 用非严格模式的立即执行函数获取this
    如果代码不在严格模式下运行,直接用IIFE获取全局this:

    var root = freeGlobal || freeSelf || (function() { return this; })();
    

    注意:如果是严格模式,这个写法的this会是undefined,需结合环境判断使用。

  • 适配Lodash原有逻辑的兼容写法
    参考Lodash本身的环境检测逻辑,写出更贴合原代码的替代方案:

    var root = freeGlobal || freeSelf || 
      (typeof window === 'object' && window) || 
      (typeof global === 'object' && global) || 
      this;
    

这些写法都避免了Function构造函数的使用,既不会触发Linter警告,也能保持多环境下的兼容性。

内容的提问来源于stack exchange,提问作者ijustlovemath

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:45:37