node.js中的exports和module.exports

來源:互聯網
上載者:User

標籤:des   c   style   class   blog   code   

不同的程式設計語言都有各自的程式碼群組織和複用的方式,如.net、php中的命名空間,python中的import,ruby中的module等,來避免命名空間汙染。一直都沒搞清楚node中的exports和module.exports的區別,藉此搞清楚node的代碼模組複用方式。

 

首先怎麼建立node中的modules。

可以直接建立一個檔案作為module,如下module.js

function writeLine(){    console.log("module.js");}exports.dbleNum=function(num){    return num*2;}exports.tripleNum=function(num){    return num*3;}

 

 其中,我們exports兩個函數,在example.js檔案中(如下),我們可以利用require就能取得這兩個函數

var module = require(‘./module‘);console.log(module.dbleNum(3));console.log(module.tripleNum(3));

 

這樣就可以用module.js中的函數了。其中./表示這模組和當前的調用模組在同一目錄下,若是放在子目錄lib下面,就是require(‘./lib/module‘),不需要尾碼.js的。

當然這是簡單的單個檔案的模組,如果是比較複雜的可以以包的形式,也即n像pm安裝的包那樣子。如上module.js檔案,我們將其放在example_module檔案夾下,裡面建立一個package.json檔案(這是是包的主要資訊),有名稱,描述,依賴,main,作者,版本等等,我們簡略一下就不寫那麼多,主要寫了如下

{  "name": "module",  "description": "example",  "version": "0.0.1",  "dependencies": {    },  "main": "module",  }

 

 一般模組中的主檔案是index.js,也就是"main":"index.js"。這裡模組我們寫的是module.js,我也就懶的改了,所以寫成了module。

var module = require(‘./example_module‘);console.log(module.dbleNum(3));console.log(module.tripleNum(3));

 

  這樣就可以調用example_module這個包了。由於不是通過npm安裝,不能直接require(‘example_module‘);自己嘗試了下,如果建立個node_modules檔案夾,把example_module放裡面,就可以直接require(‘example_module‘),應該是因為npm安裝的包也是會安裝到node_modules中的。

 

說到現在還沒說exports和module.exports的區別,囧。

如果建立了一個module,想返回其中的一個變數或者函數,將其直接賦給exports是不可以的,如下

var calcNum = function(){};calcNum.prototype.dbleNum=function(num){    return num*2;}calcNum.prototype.tripleNum=function(num){    return num*3;}exports = calcNum;

 

這樣是不可以的。但是如果可以將exports換成module.exports就是可行的。此時倒出的calcNum,如果在example.js中調用就要像下面這樣子。

var module = require(‘module‘);var test = new module;console.log(module.dbleNum(3));console.log(module.tripleNum(3));

 

 這是因為exports是module.exports的全域引用,exports.myfunc是module.exports.myfunc的縮減寫法。於是,如果將任何函數、對象、變數賦給exports就斷開了exports與module.exports的參考關聯性,而事實上module.exports是真正的出口,所以直接將變數或者函數賦給exports是不可以的(exports.myfunc=myfun是可以的,因為沒有切斷exports和module.exports的參考關聯性)。因此,在同一個module中,如果exports和module.exports同時存在,exports是會被忽略的。

 如有錯誤,歡迎指正。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.