You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 10:52:04