【问题标题】:Why is it possible to access 'module.exports' as just 'exports' but not so with 'module.id'?为什么可以像访问“exports”一样访问“module.exports”,但不能访问“module.id”?
【发布时间】:2018-01-28 10:43:52
【问题描述】:

这是我在名为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 都是 module 对象的属性。但我可以访问exports 没有module. 限定符,但我无法为id 这样做 属性。

为什么会这样?这里有什么概念使它成为可能 访问 module.exports 就像 exports 但不是这样 module.id?

【问题讨论】:

    标签: javascript node.js variables scope


    【解决方案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

    【讨论】:

    • @Lone Learner 如果这回答了您的问题,请考虑接受它作为答案。
    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多