1. 什么是 globalThis

一句话定义

globalThis 是 JavaScript 中访问全局对象的标准化方式,无论代码在什么环境下运行。

之前的混乱局面

// 不同环境下的全局对象不同
window        // 浏览器
global        // Node.js
self          // Web Workers
this          // 严格模式下 undefined
frames        // 某些情况

// 以前需要这样判断:
const getGlobal = () => {
  if (typeof window !== 'undefined') return window;
  if (typeof global !== 'undefined') return global;
  if (typeof self !== 'undefined') return self;
  return this;
};

2. globalThis 的兼容性

支持情况

  • ES2020+ 正式加入标准

  • 现代浏览器:Chrome 71+, Firefox 65+, Safari 12.1+

  • Node.js:12.0+

  • TypeScript:3.4+(lib: es2020)

// 在模块文件中(有 import/export)
// ✅ 必须用 declare global
declare global {
  // 这会扩展到全局
  interface Window {
    moduleExtendedProp: string;
  }
  
  // 也可以在模块中扩展 globalThis
  namespace globalThis {
    var moduleGlobalVar: string;
  }
  
  // 扩展 NodeJS(如果在 Node.js 模块中)
  namespace NodeJS {
    interface ProcessEnv {
      MODULE_SPECIFIC_ENV: string;
    }
  }
}

export {}; // 使文件成为模块

declare global {

  namespace globalThis {

    var myCustomProp: string;

    interface Array {

      a: number;

    }

  }

  namespace NodeJS {

    interface Process {

      a: 1;

    }

  }

}

export {};

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐