2017-03-16 51 views
0

我正在開發我的第一個NodeJS項目。當我在書本上和互聯網上閱讀時,我開始以古典的方式構建模塊。 隨着項目開始增長,我決定將模塊拆分成小型可重用組件。這導致我在文件的頂部有大量的require,並且有時候會有解決循環依賴的風險。而且,這種方法並不適合測試,因爲我必須要求所有依賴項進行測試。我問其他開發人員更好的方法來解決這個問題,他們中的大多數人建議我使用依賴注入和函數構造函數。作爲構造函數的節點模塊

假設我有ModuleA和ModuleB, ModuleC同時需要ModuleA和ModuleB。而不是要求這些模塊在頁面的頂部,我應該將它們作爲參數在構造函數中傳遞。 例如

module.exports = function ModuleC(moduleA, moduleB) { 
//module implementation here.... 
function doSomething() {} 
return { 
    doSomething 
} 
} 

這種方法的問題,起初看起來很不錯,是在應用程序的主入口點我有權要求和實例的所有模塊通過。

const ModuleA = require("./moduleA"); 
const ModuleB = require("./moduleB"); 
const ModuleC = require("./moduleC"); 

const moduleA = new ModuleA(); 
const moduleB = new ModuleB(); 


const moduleC = new ModuleC(moduleA, moduleB); 
moduleC.doSomething(); 

現在只有3個模塊,我不得不編寫7行代碼才能使用模塊的功能。如果我有20個模塊與應用程序的主要入口點一起工作將是一場噩夢。

我想這不是最好的方法,即使使用這種方法,測試也不容易。

所以,我要求你建議/解釋我在開始探索NodeJS單詞時完成我發現的這個簡單任務的最佳方式,也許比它更難。謝謝。

回答

0

如果您將所有代碼放入單個文件中,也可以實現代碼重用性。創建更小的模塊並不是唯一的解決方案。考慮寫在文件allLogic.js(let)中的以下代碼。

var allFunctions = function(){ }; 
var allFunctionsProto = allFunctions.prototype; 

allFunctionsProto.getJSONFile = function(fileName){ 
    var that = this; //use 'that' instead of 'this' 
    //code to fetch json file 
}; 


allFunctionsProto.calculateInterest = function(price){ 
    var that = this; //use 'that' instead of 'this' 
    //code to calculate interest 
}; 

allFunctionsProto.sendResponse = function(data){ 
    var that = this; //use 'that' instead of 'this' 
    //code to send response 
}; 

//similary write all of your functions here using "allFunctionsProto.<yourFunctionName>" 

module.exports = new allFunctions(); 

每當我需要得到任何JSON文件我知道邏輯得到JSON文件已經寫在allLogic.js文件,所以我需要這個模塊,並使用如下。

var allLogic = require('../path-to-allLogic/allLogic.js'); 
allLogic.getJSON(); 

這種方法比爲每項工作創建大量模塊要好得多。當然,如果模塊時間更長,您可以創建新模塊,但在這種情況下,您需要考慮問題分離,否則循環依賴將困擾您。

當你正在使用你moduleCmoduleAmoduleB,如果你把所有的moduleA,moduleB和moduleC代碼的單個模塊中,我曾指出,你可以參考裏面的功能和所有的獨立功能模塊使用that和那些也需要後纔可用。