1. 程式人生 > >nodeJs--模組module.exports與例項化方法

nodeJs--模組module.exports與例項化方法

在nodejs中,提供了exports 和 require 兩個物件,其中 exports 是模組公開的介面,require 用於從外部獲取一個模組的介面,即所獲取模組的 exports 物件。而在exports丟擲的介面中,如果你希望你的模組就想為一個特別的物件型別,請使用module.exports;如果希望模組成為一個傳統的模組例項,請使用exports.xx方法;module.exports才是真正的介面,exports只不過是它的一個輔助工具。最終返回給呼叫的是module.exports而不是exports。下面看程式碼;
首先來看module.exports,新建一個hello.js,程式碼如下:

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物件負值一個新的方法即可;見下面程式碼:

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();見程式碼:

var Hello=require('./hello');
Hello.add.say()

進行node環境,執行main.js,可以看到,結果和上面一樣,都會輸出:我的名字叫:jone,我今年28歲,月薪為:10000元;

轉載