nodejs 中 module.exports 和 exports 的区别


1. module应该是require方法中,上下文中的对象

2. exports对象应该是上下文中引用module.exports的新对象

3. exports.a = xxx 会将修改更新到module.exports对象中

4. exports = xxx 直接改变了 exports的指向,

 

module.js的474行代码:

module._compile(stripBOM(content), filename);

 

module.js的437行代码:

var wrapper = Module.wrap(content);

再往下跟:

进入node.js文件的879行:

return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];

wrapper[0]是字符串:"(function (exports, require, module, __filename, __dirname) { "

wrapper[1]是字符串:" });"

 

看到经过wrap这一步,整个自己写的index.js被包装成了一个function,而exports, require, module等等,其实都是外部传进来的对象而已

在index.js中自然可以使用

而且在module.js的439行:

var compiledWrapper = runInThisContext(wrapper, filename, true);

可见通过runInThisContext方法,将上述wrapper代码按照filename的路径生成了一个新的匿名function文件(index.js)

 

继续调试到达module.js的456行:

var args = [self.exports, require, self, filename, dirname];
return compiledWrapper.apply(self.exports, args);

我们的匿名 function : index.js终于被调用!

args对应匿名function参数:exports, require, module, __filename, __dirname

 

 

 可以参考的文章:

http://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-nodejs/7142924#7142924

http://cnodejs.org/topic/4f7523168a04d82a3d4446df

http://cnodejs.org/topic/52308842101e574521c16e06

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM