node.js自學筆記(5)-module__js

來源:互聯網
上載者:User

模組是nodejs中重要的概念 建立模組

建立一個檔案,取名為testerhome.js ,內容如下:

//testerhome.jsvar nameexports.setName = function(theName){    name = theName;};exports.sayName = function(){    console.log('Hello ' + name);};
引用模組

在同級目錄下建立一個test.js檔案

//test.jsvar testerHome = require('./testerhome');testerHome.setName('TesterHome');testerHome.sayName();

上面的檔案引用了我們定義的testerhome模組,然後設定其中屬性name的值,然後列印屬性name的值

執行上面的程式:

D:\node.js\0211>node test.jsHello TesterHomeD:\node.js\0211>
知識點 exports

第一個檔案testerhome.js中我們用到exports這個關鍵字,這個關鍵字定義的就是介面,可以供外部調用的。 單次載入

在test.js中我們使用require來載入一個模組,那如果多次載入的話會出現什麼狀況,現在修改下test.js中代碼:

//test.jsvar testerHome = require('./testerhome');testerHome.setName('TesterHome');var testerHome1 = require('./testerhome');testerHome1.setName('Tester Home2');testerHome.sayName();

上面的程式我們重新載入了一次模組並將其賦予了testerHome1變數。然後運行程式

D:\node.js\0211>node test.jsHello Tester Home2

你會驚奇的發現列印了第二個對象設定的名稱,為什麼。因為模組不會重複載入,只會覆蓋。所以整個程式只會有一個模組對象,所以上面的testerHome和testerHome1指向的都是同一個對象。 給模組添加對象

如果我們想給剛才的testerhome模組添加一個對象,如何添加呢。
請看下面的代碼:

//testerhome.jsvar nameexports.setName = function(theName){    name = theName;};exports.sayName = function(){    console.log('Hello ' + name);};function World(){    var name    this.setName = function(theName){        name = theName;    };    this.sayName = function(){        console.log('Hello ' + name);    };};exports.World = World;

如何引用這個對象,其實我們事件那一篇文章用過,當時用的是events模組中的EventEmitter對象。

我們在test.js使用該World對象:

//test.jsvar testerHome = require('./testerhome');testerHome.setName('TesterHome');testerHome.sayName();var World = require('./testerhome').World;var world = new World;world.setName('World');world.sayName();

運行該程式:

D:\node.js\0211>node test.jsHello TesterHomeHello WorldD:\node.js\0211>

還有一種方式,匯入的時候不用寫.World。直接new對象的。修改testerhome.js檔案:

//testerhome.jsvar nameexports.setName = function(theName){    name = theName;};exports.sayName = function(){    console.log('Hello ' + name);};function World(){    var name    this.setName = function(theName){        name = theName;    };    this.sayName = function(){        console.log('Hello ' + name);    };};module.exports = World;

變化的地方在於最後一句話把exports.World變成了module.exports。這樣我們在外部調用的時候就不需要再加入.World。test.js程式修改如下:

//test.jsvar World = require('./testerhome');var world = new World;world.setName('World');world.sayName();

運行該程式

D:\node.js\0211>node test.jsHello World

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.