全局作用域中this指向由环境和严格模式决定:非严格模式下浏览器为window、Node.js为global(或globalThis),严格模式或模块中为undefined;无法通过bind等方法手动绑定,应优先使用globalThis获取全局对象。

在 JavaScript 中,全局作用域里的 this 指向取决于运行环境和代码模式(严格模式与否),不是“可以手动绑定”到 window 或 global,而是由执行上下文自动决定的。
非严格模式下,全局 this 默认指向全局对象
浏览器中全局对象是 window,Node.js 中是 global(或 globalThis)。只要不在函数、模块、类或箭头函数等局部作用域内,顶层的 this 就等于它:
- 直接写
console.log(this === window);(浏览器)会输出true - 在 Node.js 文件顶层写
console.log(this === global);也返回true - ES2020 起统一可用
globalThis,跨环境更可靠
严格模式下,全局 this 是 undefined
如果脚本开头有 "use strict";,或模块(.mjs、import/export)默认启用严格模式,那么顶层 this 不再自动绑定到全局对象,而是 undefined:
"use strict"; console.log(this); // undefined- 这是有意设计,避免意外依赖全局对象
- 此时想访问全局对象,应显式用
window、global或globalThis
模块环境下 this 始终不是全局对象
ES 模块(含 type="module" 的 script)顶层的 this 总是 undefined,无论是否写 "use strict":
立即学习“Java免费学习笔记(深入)”;
- 因为模块自动启用严格模式,且有独立的词法作用域
- 想获取全局对象?用
globalThis最稳妥 - 例如:
console.log(globalThis === window); // 浏览器中 true
不要试图“绑定”全局 this
call、apply、bind 对全局作用域的 this 无效——它们只影响函数调用时的 this,不能修改顶层执行上下文的 this 值:
this.bind(window); // 无意义,this 不是函数function foo() { return this; }.bind(window)(); // 这样才生效,但只对函数有用- 全局代码里没有“调用者”,所以不存在可绑定的函数上下文
不复杂但容易忽略:全局 this 的行为由环境 + 模式决定,而不是靠绑定。需要全局对象时,优先用 globalThis。



















