在此页面(http://docs.nodejitsu.com/articles/getting-started/what-is-require)上,它声明"如果要将导出对象设置为函数或新对象,则必须使用module.exports对象."
我的问题是为什么.
// right
module.exports = function () {
console.log("hello world")
}
// wrong
exports = function () {
console.log("hello world")
}
Run Code Online (Sandbox Code Playgroud)
我console.log结果(result=require(example.js)),第一个是[Function]第二个{}.
你能解释一下背后的原因吗?我在这里阅读帖子:在Node.js中的module.exports vs exports.它很有帮助,但没有解释它以这种方式设计的原因.如果直接退回出口参考会有问题吗?
这是2个文件:
// main.js
require('./modules');
console.log(name); // prints "foobar"
// module.js
name = "foobar";
Run Code Online (Sandbox Code Playgroud)
当我没有"var"时,它可以工作.但是当我有:
// module.js
var name = "foobar";
Run Code Online (Sandbox Code Playgroud)
名称将在main.js中未定义.
我听说全局变量很糟糕,你最好在引用之前使用"var".但这是全球变量好的情况吗?