Node.js中的模組介面module.exports淺析

來源:互聯網
上載者:User

Node.js中的模組介面module.exports淺析
在寫node.js代碼時,我們經常需要自己寫模組(module)。同時還需要在模組最後寫好模組介面,聲明這個模組對外暴露什麼內容。實際上,node.js的模組介面有多種不同寫法。這裡作者對此做了個簡單的總結。   返回一個JSON Object 如下代碼是一個簡單的樣本。  1 var exp = { 2   "version": "1.0.0", 3   "function1": null, 4   "module1": null,5 };6 module.exports = exp;   這種方式可以用於返回一些全域共用的常量或者變數,例如   1 // MATH.js2 var MATH = {3   "pi": 3.14,4   "e": 2.72,5 };6 7 module.exports = MATH;   調用方式為  1 var MATH = require("./MATH")2 console.log(MATH.pi);  這種方式還可以用於返回幾個require的其他模組,可以實現一次require多個模組  1 // module_collection.js2 var module_collection = {3   "module1": require("./module1"),4   "module2": require("./module2"),5 };6 7 module.exports = module_collection; 調用方式為 1 var module_collection = require("./module_collection");2 var module1 = module_collection.module1;3 var module2 = module_collection.module2;4 // Do something with module1 and module2  其實這種方式還有個變種,如下,通常可以返回幾個函數  1 // functions.js 2 var func1 = function() { 3   console.log("func1"); 4 }; 5  6 var func2 = function() { 7   console.log("func2"); 8 }; 9 10 exports.function1 = func1;11 exports.function2 = func2; 調用方式為 1 var functions = require("./functions");2 functions.function1();3 functions.function2();  返回一個建構函式,也就是一個類 如下是一個簡單的樣本。   1 // CLASS.js 2 var CLASS = function(args) { 3   this.args = args; 4 } 5  6 CLASS.prototype.func = function() { 7   console.log("CLASS.func"); 8   console.log(this.args); 9 };10 11 module.exports = CLASS;   調用方法為 1 var CLASS = require("./CLASS")2 var c = new CLASS("arguments");  返回一個普通函數 如下是一個簡單的樣本  1 // func.js2 var func = function() {3   console.log("this is a testing function");4 };5 6 module.exports = func;   調用方法為 1 var func = require("./func");2 func();  返回一個對象object 如下是一個簡單的樣本   1 // CLASS.js 2 var CLASS = function() { 3   this.say_hello = "hello"; 4 }; 5  6 CLASS.prototype.func = function() { 7   console.log("I say " + this.say_hello); 8 }; 9 10 module.exports = new CLASS();  調用方法為 1 var obj = require("./CLASS");2 obj.func();  單例模式 有時候我們需要模組返回一個單例 singleton. 可以利用上面的方式1和方式4來實現。也就是如下兩種形式  1 // MATH.js2 var MATH = {3   "pi": 3.14,4   "e": 2.72,5 };6 7 module.exports = MATH; 以及   1 // CLASS.js 2 var CLASS = function() { 3   this.say_hello = "hello"; 4 }; 5  6 CLASS.prototype.func = function() { 7   console.log("I say " + this.say_hello); 8 }; 9 10 module.exports = new CLASS();  最後,真的很喜歡JavaScript這個語言,很方便。而且node.js的出現極大的增強了這門語言的能力。看好它!

聯繫我們

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