JavaScript中全局this指向因环境和模式而异:浏览器非严格模式指向window,Node.js指向module.exports,严格模式下为undefined;推荐统一使用globalThis。

在 JavaScript 中,全局对象里的 this 指向取决于执行环境和代码模式,不是固定不变的。
浏览器环境中的全局 this
在非严格模式下,顶层(即不在函数内)的 this 指向 window 对象:
console.log(this === window); // true- 所有用
var声明的全局变量,都会成为window的属性,也能通过this访问
Node.js 环境中的全局 this
在 Node.js 模块中,顶层的 this 不等于 global,而是指向当前模块的 module.exports:
console.log(this === module.exports); // true-
this.foo = 'bar';等价于module.exports.foo = 'bar'; - 若想访问真正的全局对象,需显式使用
global(Node.js)或globalThis
严格模式下的变化
开启 "use strict" 后,全局作用域中 this 不再自动绑定到全局对象:
立即学习“Java免费学习笔记(深入)”;
"use strict"; console.log(this); // undefined- 函数内部也一样:独立调用的函数中 this 是
undefined,不再是window或global
统一可靠的访问方式:globalThis
ES2020 引入了 globalThis,它在所有环境中都指向当前执行上下文的全局对象:
console.log(globalThis === window); // 浏览器中为 trueconsole.log(globalThis === global); // Node.js 中为 true- 推荐用
globalThis替代直接依赖this或环境特定对象
不复杂但容易忽略:不要默认认为全局 this 总是可用或总是指向预期对象,尤其在跨环境或启用严格模式时。


















