Node.js之exports與module.exports

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

 module.exports = {};
Node.js爲了方便地導出功能函數,node.js會自動地實現如下這個語句

tool.jsjava

 exports.a = function(){
 console.log('a')
 }

 exports.a = 1
test.js
 var x = require('./tool');

 console.log(x.a)
 

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

再看看下面例子express

hammer.jsapp

 exports.a = function(){
  console.log('a')
 }

 module.exports = {a: 2}
 exports.a = 1
 

test.jsmongoose

 var x = require('./hammer');

 console.log(x.a)
 

result:ide

 2

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

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

##module.exports = Viewthis

function View(name, options) { 
   options = options || {};
   this.name = name;
   this.root = options.root;
   var engines = options.engines;
   this.defaultEngine = options.defaultEngine;
   var ext = this.ext = extname(name);
   if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no         extension was provided.');
   if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') +     this.defaultEngine);
   this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
   this.path = this.lookup(name);
 }

 module.exports = View;
 

javascript裏面有一句話,函數即對象,View 是對象,module.export =View, 即至關於導出整個view對象。外面模塊調用它的時候,可以調用View的全部方法。不過須要注意,只有是View的靜態方法的時候,纔可以被調用,prototype建立的方法,則屬於View的私有方法。

tool.js

function View(){

 }

 View.prototype.test = function(){
  console.log('test')
 }

 View.test1 = function(){
  console.log('test1')
 }

 

module.exports = View

test.js

 var x = require('./tool');

 console.log(x) //{ [Function: View] test1: [Function] }
 console.log(x.test) //undefined
 console.log(x.test1) //[Function]
 x.test1() //test1

##var app = exports = module.exports = {};

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

 exports = module.exports = createApplication;

 /**
  * Expose mime.
  */

 exports.mime = connect.mime;
 

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

##exports.init= function(){}

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

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

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

相關文章
相關標籤/搜索