zoukankan      html  css  js  c++  java
  • Node.js 中 exports 和 module.exports 的区别

    1. 每一个模块中都有一个 module 对象, module 对象中有一个 exports 对象
    2. 我们可以把需要导出的成员都放到 module.exports 这个接口对象中,也就是 module.exports.xxx = xxx 的方式
    3. 但是,这样显得特别麻烦,为了方便操作,在每一个模块中又提供了一个叫 exports 的成员
    4. 所以,有了这样的等式: module.exports === exports
    5. 所以,对于:module.exports.xxx = xxx 的方式等价于 exports.xxx = xxx
    6. 当一个模块需要导出单个成员的时候,必须要使用 module.exports = xxx
    7. 因为每个模块最终向外 return 的是 module.exports,而 exports 只是 module.exports 的一个引用,所以即便你为 exports = xxx 重新赋值,也不会影响 module.exports

    重新建立引用关系:

    exports = module.exports;

    导出多个成员(必须在对象中):

    • 方法一(使用 exports):
          exports.a = 123;
          exports.b = 'hello';
          exports.c = () => {
              console.log('ccc');
          };
          exports.d = {
              foo: 'bar'
          };
    • 方法二(使用module.exports):
          module.exports = {
              add: (x, y) => {
                  return x + y;
              },
              str: 'hello'
          };

    导出单个成员(拿到的直接就是 字符串, 数字 等):

      

    module.exports = 'hello';

    但是的话,因为只能导出单个成员,所以会出现覆盖情况,如下所示:

        module.exports = 'hello';
    
        // 以这个为准,后者会覆盖前者
        module.exports = (x, y) => {
            return x + y;
        };

     

  • 相关阅读:
    统计单词数 OpenJ_Bailian
    整数划分 NBUT
    高精度(x ,/, +, -, %)良心模板
    binary-tree-maximum-path-sum
    2080 特殊的质数肋骨 USACO (深度优先搜索)
    1413 权势二进制
    POJ 1258
    poj 3126
    hdu 1195
    POJ 3752
  • 原文地址:https://www.cnblogs.com/duxiu-fang/p/11147658.html
Copyright © 2011-2022 走看看