在nodejs中,提供了exports 和 require 兩個對象,其中 exports 是模塊公開的接口,require 用於從外部獲取一個模塊的接口,即所獲取模塊的 exports 對象。而在exports拋出的接口中,若是你但願你的模塊就想爲一個特別的對象類型,請使用module.exports;若是但願模塊成爲一個傳統的模塊實例,請使用exports.xx方法;module.exports纔是真正的接口,exports只不過是它的一個輔助工具。最終返回給調用的是module.exports而不是exports。下面看代碼;
首先來看module.exports,新建一個hello.js,代碼以下:node
module.exports=function(name,age,money){ this.name=name; this.age=age; this.money=money; this.say=function(){ console.log('個人名字叫:'+this.name+',我今年'+this.age+'歲,月薪爲:'+this.money+'元;') } };
能夠看到,module.exports被賦予了一個構造函數;再新建一個main.js,其中引入hello.js這個模塊,把exports方法接受進來,main.js代碼以下:函數
var Hello=require('./hello'); var hello=new Hello('jone','28','10000') hello.say();
進入node環境,運行main.js,能夠看到,已經打印出來:個人名字叫:jone,我今年28歲,月薪爲:10000元;
而在hello.js中,咱們是賦予了exports一個函數 ,固然,也能夠採用匿名函數的方式;見代碼:工具
function hello(name,age,money){ this.name=name; this.age=age; this.money=money; this.say=function(){ console.log('個人名字叫:'+this.name+',我今年'+this.age+'歲,月薪爲:'+this.money+'元;') } } module.exports=hello;
以上modle.exports,這個模塊很明顯是一個特別的對象模型;那若是採用對象實例的方法該如何實現呢?其實也很簡單,只須要給exports對象負值一個新的方法便可;見下面代碼:ui
function hello(name,age,money){ this.name=name; this.age=age; this.money=money; this.say=function(){ console.log('個人名字叫:'+this.name+',我今年'+this.age+'歲,月薪爲:'+this.money+'元;') } } var Hello=new hello('jone','28','10000'); exports.add=Hello
在hello.js中,依然是一個構造函數,聲明瞭一個變量Hello,而後再把Hello賦值給exports自定義的add方法;那麼在main.js中,因爲add已是exports的一個自定義的實例方法了,所以咱們能夠直接這麼調用它:Hello.add.say();見代碼:this
var Hello=require('./hello'); Hello.add.say()
進行node環境,運行main.js,能夠看到,結果和上面同樣,都會輸出:個人名字叫:jone,我今年28歲,月薪爲:10000元;code