随机查看source file在 NodeJS
的 express
框架中,有两行代码我不明白(这些代码行是几乎所有 NodeJS 文件的典型代码)。
/**
* Expose `Router` constructor.
*/
exports = module.exports = Router;
和
/**
* Expose HTTP methods.
*/
var methods = exports.methods = require('./methods');
我了解第一段代码 允许将文件中的其余函数暴露给NodeJS应用程序,但我不完全了解< strong>它是如何工作的,或者该行中的代码是什么意思。
What do
exports
andmodule.exports
actually mean?
我相信第二段代码允许文件中的函数访问方法
,但同样,它究竟是如何做到这一点的。
基本上,这些神奇的词是什么:module
和exports
?
最佳答案
更具体一点:
module
是文件内的全局范围变量。
所以如果你调用 require("foo")
那么:
// foo.js
console.log(this === module); // true
它的作用与 window
在浏览器中的作用相同。
还有另一个名为 global
的全局对象,你可以在任何你想要的文件中写入和读取,但这涉及到改变全局范围,这就是 EVIL
exports
是一个存在于 module.exports
上的变量。它基本上是您在需要文件时导出的内容。
// foo.js
module.exports = 42;
// main.js
console.log(require("foo") === 42); // true
exports
本身存在一个小问题。 _global 范围 context+ 和 module
不 相同。 (在浏览器中,全局作用域上下文和 window
是一样的)。
// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with
// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports
// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works
关于javascript - NodeJS/Express 中的 "module.exports"和 "exports.methods"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6116960/