[英]Functions in Node.js modules
I can define a module in node.js: 我可以在node.js中定义一个模块:
mymodule.js mymodule.js
exports.bar = "Hello";
exports.foo = function(){
console.log(exports.bar);
}
I can require the module: 我可以要求该模块:
app.js app.js
var baz = require("./mymodule.js");
baz.foo(); //Logs "Hello" in the console
If I call the foo
function as above, it logs "Hello"
in the console. 如果我按上述方式调用
foo
函数,它将在控制台中记录"Hello"
。 However, the variable that foo
is logging is exports.bar
, not baz.bar
. 然而,变量
foo
是日志记录exports.bar
,不baz.bar
。 Does Node.js automatically know to switch them or the exports
object still exists? Node.js是否自动知道要切换它们,还是
exports
对象仍然存在?
exports
is a special object which is included in every JS
file in the Node.js
application by default. 默认情况下,
exports
是一个特殊对象,它包含在Node.js
应用程序的每个JS
文件中。
So anything you export in a file ( mymodule.js
in your case) is a property on this object and when you require
this module export
object is assigned to the requiring object ( baz
in your case). 因此,导出到文件中的所有内容(在您的情况下为
mymodule.js
)都是该对象的属性,当您require
此模块时, export
对象将分配给需要的对象(在您的情况下为baz
)。
When you do 当你做
var baz = require("./mymodule.js");
Your baz
variable now looks like something 您的
baz
变量现在看起来像
baz = {
bar : "Hello",
foo : () => {
console.log(baz.bar)
}
}
And when you call baz.foo()
you see "Hello"
printed 当您调用
baz.foo()
您会看到"Hello"
当您在模块中使用导出时,这将为对象添加属性,并将其像本地对象(变量)一样使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.