模块脚本中this值在Firefox控制台与代码输出不一致问题咨询
问题分析:模块脚本调试时Firefox与Chrome的
this差异 结论
这是Firefox的预期行为,并非bug,属于浏览器调试器的实现差异。
详细解释
模块脚本本身的
this规范
根据ES模块规范,模块顶层的this值为undefined,所以代码中的console.log(this)输出undefined完全符合规范要求。调试器控制台的执行环境差异
- Firefox调试器在暂停代码时,控制台默认运行在**全局上下文(Window)**中,此时输入
this自然返回Window对象。 - Chrome调试器在暂停于模块脚本时,控制台会继承模块的执行上下文,因此
this保持为undefined。
这种差异是两款浏览器调试工具的设计选择不同,并不违反ES模块的规范要求。
示例代码
<!DOCTYPE html> <html> <head> <title>check-this</title> <meta charset="utf-8"> <script type="module"> console.log(this); // undefined </script> </head> </html>
Firefox调试控制台输出
>>this Window https://example.com/check-this.html
Chrome调试控制台输出
>>this undefined
内容的提问来源于stack exchange,提问作者twisted
相关产品推荐
相关产品推荐

