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元;

轉載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章