zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    JSP第三章
    JSP第二章
    JSP第一章
    异常
    七种设计原则
    非泛型集合
    .NET第一章
    航班预定系统
    JSP数据交互(二)
    JSP数据交互(一)
  • 原文地址:https://www.cnblogs.com/vincedotnet/p/3439975.html
Copyright © 2011-2022 走看看