1. 程式人生 > >module.exports與exports

module.exports與exports

根據 blank cno reat default div fun options eap

API文檔是枯燥的,下面本人收集了一些論壇經常有人疑問和開源代碼中經常遇到的案例供大家研究一下。

module.exports與exports的區別

每一個node.js執行文件,都自動創建一個module對象,同時,module對象會創建一個叫exports的屬性,初始化的值是 {}

 module.exports = {};

Node.js為了方便地導出功能函數,node.js會自動地實現以下這個語句

foo.js

1  exports.a = function(){
2  console.log(‘a‘)
3  }
4 
5  exports.a = 1

test.js

1  var
x = require(‘./foo‘); 2 console.log(x.a)

看到這裏,相信大家都看到答案了,exports是引用 module.exports的值。module.exports 被改變的時候,exports不會被改變,而模塊導出的時候,真正導出的執行是module.exports,而不是exports

再看看下面例子

foo.js

1 exports.a = function(){
2   console.log(‘a‘)
3  }
4  module.exports = {a: 2}
5  exports.a = 1

test.js

1  var x = require(‘./foo‘);
2 console.log(x.a)

result:

 2

exports在module.exports 被改變後,失效。

是不是開始有點廓然開朗,下面將會列出開源模塊中,經常看到的幾個使用方式。

module.exports = View

 1 function View(name, options) { 
 2    options = options || {};
 3    this.name = name;
 4    this.root = options.root;
 5    var engines = options.engines;
 6    this.defaultEngine = options.defaultEngine;
7 var ext = this.ext = extname(name); 8 if (!ext && !this.defaultEngine) throw new Error(‘No default engine was specified and no extension was provided.‘); 9 if (!ext) name += (ext = this.ext = (‘.‘ != this.defaultEngine[0] ? ‘.‘ : ‘‘) + this.defaultEngine); 10 this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); 11 this.path = this.lookup(name); 12 } 13 14 module.exports = View;

javascript裏面有一句話,函數即對象,View 是對象,module.export =View, 即相當於導出整個view對象。外面模塊調用它的時候,能夠調用View的所有方法。不過需要註意,只有是View的靜態方法的時候,才能夠被調用,prototype創建的方法,則屬於View的私有方法。

foo.js

1  function View(){
2 
3  }
4  View.prototype.test = function(){
5   console.log(‘test‘)
6  }
7  View.test1 = function(){
8   console.log(‘test1‘)
9  }

module.exports = View

test.js

1  var x = require(‘./foo‘);
2  console.log(x) //{ [Function: View] test1: [Function] }
3  console.log(x.test) //undefined
4  console.log(x.test1) //[Function]
5  x.test1() //test1
var app = exports = module.exports = {};

其實,當我們了解到原理後,不難明白這樣的寫法有點冗余,其實是為了保證,模塊的初始化環境是幹凈的。同時也方便我們,即使改變了 module.exports 指向的對象後,依然能沿用 exports的特性

1  exports = module.exports = createApplication;
2  /**
3   * Expose mime.
4   */
5  exports.mime = connect.mime;

例子,當中 module.exports = createApplication 改變了module.exports了,讓exports失效,通過exports = module.exports的方法,讓其恢復原來的特點。

exports.init= function(){}

這種最簡單,直接就是導出模塊 init的方法。

var mongoose = module.exports = exports = new Mongoose;

集多功能一身,不過根據上文所描述的,大家應該不能得出答案。

原文地址:https://cnodejs.org/topic/52308842101e574521c16e06

module.exports與exports