Node.js 中 module.exports 和 exports 的区分

Node.js中最经常运用的生怕就是 require, exports 以及 module.exports 了,那末 exports 和 module.exports 这两者有什么区别,在什么情况下运用 exports,又在什么时刻运用 module.exports。

先举个官网的例子:

// circle.js
var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

在 circle.js 中写的源字符串是上面贴出的代码,但是现实 Node.js 在加载的时刻会在原字符串上表面拼出一个闭包,拼出以后的代码以下(有想相识为何会拼出这个代码的朋侪,请看我之前一篇文章):

(function(exports, require, module, __dirname, __filename) {
    // circle.js
    var PI = Math.PI;
    
    exports.area = function (r) {
      return PI * r * r;
    };
    
    exports.circumference = function (r) {
      return 2 * PI * r;
    };
})

Node.js 挪用这段代码的为:

function Module(id, parent) {
  this.id = id;
  this.exports = {};
  this.parent = parent;
  if (parent && parent.children) {
    parent.children.push(this);
  }

  this.filename = null;
  this.loaded = false;
  this.children = [];
}


Module.prototype._compile = function(content, filename) {
  var self = this;

  function require(path) {
    return self.require(path);
  }

  var dirname = path.dirname(filename);

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

从上面这段代码能够看到 exports 是 module 的一个属性,exports 值为 {}。在拼接以后的代码中,给这个函数传入的 exports 是 module.exports, 也就是说 exports 和 modules.exports 援用的是同一个对象。假如我们给 exports 增添属性,那末由于 modules.exports 也会增添雷同的属性,此时 modules.exports === exports。但是假如对 exports 赋值的话,那末就会形成 modules.exports 和 exports 不指向同一个对象,此时再对 exports 做任何行动都跟 modules.exports 没有任何关系了,用一段代码模仿就是:

var module = { exports: {}};
var exports = module.exports;
exports.a = 1;
console.log(module.exports); // {a: 1}

exports = {b:2};
console.log(module.exports); // {a: 1}

所以从上面的代码能够看出,假如我们想在模块文件中供应其他模块能够接见的接口,最好写成
exports[“key”] = value 或许 module.exports = {key: value} 的情势, 总之别对 exports 赋值。

    原文作者:zwhu
    原文地址: https://segmentfault.com/a/1190000004157460
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞