【问题标题】:modules.exports is the same as "this" in CommonJs?modules.exports 与 CommonJs 中的“this”相同吗?
【发布时间】:2020-01-16 04:44:25
【问题描述】:

我不小心在一个打算与浏览器一起使用的 javascript 模块上使用了require()。 模块集this['libraryName'] = ...。 我注意到它实际上工作

所以,我创建了 2 个文件:

test1.js

console.log( require('./test2.js'))

test2.js

console.log(this === module.exports)
this.SOMETHING = 10

结果?

$ node ./test1.js 
true
{ SOMETHING: 10 }
$

我没想到会这样! true 意味着 module.exports 在全局上下文中与 this 相同。

  • 这是新的吗?
  • 这是规范的一部分吗?
  • 这不是让创建在导入或需要时可以使用的文件变得非常容易吗?
  • 如果这可行,为什么我们还要检查typeof require === 'undefined'
    • 我有没有忘记这么重要的事情?

【问题讨论】:

  • 嘿,这很可能是因为 require() 调用了模块缓存,这就是为什么它看起来像是在模拟它是全局的you can read the last paragrap here about it
  • 不知道模块缓存和它有什么关系,最后一段无关...

标签: javascript commonjs


【解决方案1】:
  1. 这并不新鲜:
    1. What is the 'global' object in NodeJS
    2. Meaning of "this" in node.js modules and functions
    3. Why does a module level return statement work in Node.js?
  2. 这不是规范的一部分https://nodejs.org/api/globals.html#globals_global

    这意味着在浏览器中,如果您在全局范围 var 中,某些东西将定义一个全局变量。在 Node.js 中,这是不同的

    当有些东西不同时,它们绝对不是任何规范的一部分。

  3. 这不是让创建在导入或需要时可以使用的文件变得非常容易吗?

    不知道怎么做。在 node.js 中,this.SOMETHING = 10 仅将一个名称 (module.exports) 更改为另一个名称 (this)。仅此而已。
    如果您尝试使用 webpack 或 <script type="module" src="..."></script>test2.js 导入浏览器,则在这两种情况下都会得到 TypeError: undefined has no properties

  4. typeof require === 'undefined'

    也许你最好使用browser-requirebrowserify 或类似的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-03
    • 2018-11-23
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2018-11-21
    相关资源
    最近更新 更多