CommonJS与ES Modules中call(null/undefined)的this行为差异原因解析
CommonJS与ES模块中this指向差异的原因解析
测试代码
console.log(this); function getThis() { console.log("this", this); } getThis.call(null); getThis.call(undefined);
1. 无严格模式的CommonJS模块(.cjs)输出:{}、全局对象、全局对象
- 模块顶层
this:CommonJS模块的顶层执行环境中,this指向当前模块的module.exports对象,初始状态下该对象为空,所以第一个输出是空对象{}。 - 函数调用的
this:非严格模式下,当通过call给函数传入null或undefined作为this绑定值时,JS引擎会自动将this替换为全局对象(Node.js环境中为globalThis),因此两次call调用都会输出全局对象。
2. ES模块(.mjs)输出:undefined、null、undefined
- 模块顶层
this:ES模块的规范明确规定,顶层执行环境中的this值为undefined,和CommonJS模块的模块机制完全不同。 - 函数调用的
this:ES模块默认运行在严格模式下,即使没有显式声明'use strict'也会遵循严格模式规则。严格模式中,函数调用时如果指定this为null或undefined,this会保持传入的原值,不会被替换为全局对象,因此传null输出null,传undefined输出undefined。
3. 开启严格模式的CommonJS模块输出:{}、null、undefined
- 模块顶层
this:严格模式不会影响CommonJS模块顶层this的指向,它依然指向当前模块的module.exports(初始为空对象{}),所以第一个输出不变。 - 函数调用的
this:开启严格模式后,函数内部的this遵循严格模式规则,通过call传入null或undefined时,this会保持传入的值,不再自动替换为全局对象,因此输出对应的null和undefined。
内容的提问来源于stack exchange,提问作者Arman Lalani
相关产品推荐
相关产品推荐

