为什么可以将'module.exports'作为'exports'访问,但不能使用'module.id'访问?

时间:2017-08-20 05:30:39

标签: javascript node.js variables scope

这是我在名为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

这是我无法理解的。 exportsid都是。{1}}和module exports对象的属性。但我可以访问module. 没有id限定符,但我无法对module.exports这样做 属性。

为什么会这样?这里有什么概念可以实现 仅exports访问module.id,但不是这样 python setup.py sdist upload -r pypi

1 个答案:

答案 0 :(得分:1)

这就是NodeJS的行为方式。您编写的每个代码最终都会被包含在具有一些特定参数的自调用函数中。

(function(exports, require, module, __filename, __dirname) {
    // your code
})()

这就是为什么即使modulerequire也可以直接使用。

  

为什么会这样?这里有什么概念可以将module.exports作为导出进行访问,但对于module.id却不是这样?

并不是说您可以访问模块的属性,而是为了便于访问而明确提供了exports

重要说明: exportsmodule.exports具有相同的引用,这意味着对任何一个的更改都会反映在其他内容上。

NodeJS文档https://nodejs.org/api/modules.html#modules_the_module_wrapper

更多参考https://www.youtube.com/watch?v=9WUFqLwfUwM&list=PLKT6oJQ4t2f-sL50I51a64jBoCknFFJy9

相关问题