Even though question has been answered and accepted long ago, i just want to share my 2 cents:
(即使问题早已得到回答和接受,我也只想分享我的2美分:)
You can imagine that at the very beginning of your file there is something like (just for explanation):
(您可以想象,在文件的开头有类似的内容(仅供说明):)
var module = new Module(...);
var exports = module.exports;
So whatever you do just keep in mind that module.exports
and NOT exports
will be returned from your module when you're requiring that module from somewhere else.
(所以,不管你做什么只是记住, module.exports
和NOT exports
将从您的模块,当你需要从别的地方该模块被退回。)
So when you do something like:
(因此,当您执行以下操作时:)
exports.a = function() {
console.log("a");
}
exports.b = function() {
console.log("b");
}
You are adding 2 function a
and b
to the object on which module.exports
points too, so the typeof
the returning result will be an object
: { a: [Function], b: [Function] }
(要添加2功能a
和b
,以在其上对象module.exports
太点,所以typeof
返回的结果将是一个object
: { a: [Function], b: [Function] }
)
Of course, this is the same result you will get if you are using module.exports
in this example instead of exports
.
(当然,这是同样的结果,如果你使用的是你会得到module.exports
在这个例子中,而不是exports
。)
This is the case where you want your module.exports
to behave like a container of exported values.
(在这种情况下,您希望您的module.exports
表现得像一个导出值的容器。)
Whereas, if you only want to export a constructor function then there is something you should know about using module.exports
or exports
;(Remember again that module.exports
will be returned when you require something, not export
).(而如果只想导出构造函数,那么使用module.exports
或exports
应该有一些知识;(再次记住, module.exports
将在需要时返回,而不是export
)。)
module.exports = function Something() {
console.log('bla bla');
}
Now typeof
returning result is 'function'
and you can require it and immediately invoke like:
(现在, typeof
返回的结果是'function'
,您可以要求它并立即调用:)
var x = require('./file1.js')();
because you overwrite the returning result to be a function.(因为您将返回结果覆盖为一个函数。)
However, using exports
you can't use something like:
(但是,使用exports
不能使用类似以下内容的东西:)
exports = function Something() {
console.log('bla bla');
}
var x = require('./file1.js')(); //Error: require is not a function
Because with exports
, the reference doesn't point anymore to the object where module.exports
points, so there is not a relationship between exports
and module.exports
anymore.
(因为与exports
,参考已不指向该对象module.exports
点,所以没有之间的关系exports
和module.exports
了。)
In this case module.exports
still points to the empty object {}
which will be returned.(在这种情况下, module.exports
仍指向将返回的空对象{}
。)
Accepted answer from another topic should also help: Does Javascript pass by reference?
(接受的另一个主题的答案也应该有所帮助: Javascript是否通过引用传递?)