• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Whokay 必ず勝つ!頑張ろう!
博客园    首页    新随笔    联系   管理    订阅  订阅
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

 

 

posted on 2013-11-24 14:16  Vince  阅读(3570)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3