exports和module.exports的区别
发布于 12 年前 作者 xiaozhouzhou 20613 次浏览 最后一次编辑是 8 年前

exports.start = start; 这个我就懂得了, exports.Manager = require(’./manager’); 这句我就不懂得了,

还有module.exports和exports有什么区别啊,很多时候看他们这样写 exports = module.exports = Manager;

7 回复
  • exports.Manager = require(’./manager’); 是先引入’./manager’这个module,它可能是一个目录或文件,看你的实现而定,然后将它赋给Manager,在export出去共其它模块require(注意,require的其实是module.exports)
  • 在一个模块(如nodejs文件)中,如果一开始没有做任何操作,那么exports===module.exports,也就是说exports是指向的module.exports的引用。
  • 我觉得两个还是不要混用的好,忘记了就容易出现问题,我一般都这样用,exports.=

这篇文章貌似说得很清楚了~

Here is an eye-opener - module.exports is the real deal. exports is just module.exports’s little helper. Your module returns module.exports to the caller ultimately, not exports. All exports does is collect properties and attach them to module.exports IF module.exports doesn’t have something on it already. If there’s something attached to module.exports already, everything on exports is ignored.
So you get the point now - if you want your module to be of a specific object type, use module.exports; if you want your module to be a typical module instance, use exports.
Having said that, exports is the recommended object unless you are planning to change the object type of your module from the traditional ‘module instance’ to something else.
E文不好,就不翻译了,直接贴上重点~~

每个模块在被require的时候都被做了头尾包装。这个方法执行后,将exports对象返回给引用方。你可以看到exports是通过参数传递进来的。如果exports整个引用被改了,那么返回的将是原来的对象。所以这个时候需要module.exports来代替。

(function (exports, require, module, __filename, __dirname) {
    var circle = require('./circle.js');
    console.log('The area of a circle of radius 4 is ' + circle.area(4));
});

exports指向module.exports,而且require方法返回的就是module.exports。所以我就奇怪了为什么还需要exports,直接用module.exports不就行了吗

@lovekugua 默认module.exports 是一个 {}。 如果你只是添加方法或属性,只要操作exports就可以了。只有需要覆盖它的时候才需要module.exports. 因为exports是形参。形参的引用只能在作用域内改变。出了作用域,将会被还原。所以想覆盖的时候,需要module.exports.

回到顶部