在 JavaScript 中,全局对象(Global Object)是预定义的对象,提供了可在任何地方使用的变量和函数。在浏览器环境中,全局对象是 window;在 Node.js 环境中,全局对象是 global。
在浏览器中,所有全局变量和函数都是 window 对象的属性:
var globalVar = "Hello";
console.log(window.globalVar); // "Hello"
function globalFunc() {
console.log("This is a global function");
}
window.globalFunc(); // "This is a global function"
在 Node.js 中,全局对象是 global:
global.globalVar = "Hello Node.js";
console.log(globalVar); // "Hello Node.js"
Infinity - 表示无穷大的数值NaN - 表示非数字值(Not-a-Number)undefined - 表示未定义的值globalThis - 在浏览器和 Node.js 中引用全局对象的标准化方式编码/解码函数
encodeURI() / decodeURI()encodeURIComponent() / decodeURIComponent()数值处理
isNaN() - 检查值是否为 NaNisFinite() - 检查值是否为有限数parseInt() - 将字符串解析为整数parseFloat() - 将字符串解析为浮点数其他函数
eval() - 执行字符串中的 JavaScript 代码(不推荐使用)setTimeout() / clearTimeout() - 定时器函数setInterval() / clearInterval() - 间隔定时器函数Promise - 处理异步操作Symbol - 创建唯一值Map, Set, WeakMap, WeakSet - 集合对象Proxy, Reflect - 元编程功能在全局执行上下文中,this 指向全局对象:
console.log(this === window); // 浏览器中为 true
console.log(this === global); // Node.js 中为 true
globalThis 是 ES2020 新增的,用于统一不同环境下的全局对象访问方式// 跨环境访问全局对象
const theGlobalObject =
typeof globalThis !== 'undefined' ? globalThis :
typeof window !== 'undefined' ? window :
typeof global !== 'undefined' ? global :
typeof self !== 'undefined' ? self : {};
热门推荐:
0