这是我在名为 foo.js
的文件中的代码。
console.log('module.exports:', module.exports)
console.log('module.id:', module.id)
console.log('exports:', exports)
console.log('id:', id)
这是我得到的输出。
$ node foo.js
module.exports: {}
module.id: .
exports: {}
/home/lone/foo.js:4
console.log('id:', id)
^
ReferenceError: id is not defined
at Object.<anonymous> (/home/lone/foo.js:4:20)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3
这是我无法理解的。 exports
和 id
都是
module
对象的属性。但我可以访问 exports
没有 module.
限定符,但我无法对 id
这样做
属性。
为什么会这样呢?这里有哪些概念使之成为可能
访问 module.exports
只是 exports
但不是这样
module.id
?
最佳答案
这就是 NodeJS 的行为方式。您编写的每个代码最终都会被包装到带有一些特定参数的自调用函数中。
(function(exports, require, module, __filename, __dirname) {
// your code
})()
这就是为什么 module
和 require
都可以直接供您使用。
Why is it so? What are the concepts at play here that makes it possible to access module.exports as just exports but not so with module.id?
这并不是说您可以访问模块的属性,而是为了方便访问而明确提供了 exports
。
重要提示: exports
和 module.exports
具有相同的引用,这意味着对其中任何一个的任何更改都会影响另一个。
NodeJS 文档:https://nodejs.org/api/modules.html#modules_the_module_wrapper
更多引用:https://www.youtube.com/watch?v=9WUFqLwfUwM&list=PLKT6oJQ4t2f-sL50I51a64jBoCknFFJy9
关于javascript - 为什么可以将 'module.exports' 作为 'exports' 访问,但不能使用 'module.id' 访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45778789/