2012-01-26 16 views
9

मैं एक नोड्स.जेएस नोब हूं और मैं मॉड्यूल संरचनाओं के आसपास अपना सिर प्राप्त करने की कोशिश कर रहा हूं। मैं testFunc() thusly विधि कॉल करने का प्रयासमॉड्यूल निर्यात वर्ग Nodes.js

var testModule = { 
    input : "", 
    testFunc : function() { 
     return "You said: " + input; 
    } 
} 

exports.test = testModule; 

: इस प्रकार अब तक मैं एक मॉड्यूल (testMod.js) इस वर्ग के निर्माण में परिभाषित किया गया है

var test = require("testMod"); 
test.input = "Hello World"; 
console.log(test.testFunc); 

लेकिन मैं एक लेखन त्रुटि मिलती है:

TypeError: Object #<Object> has no method 'test' 

मैं क्या गलत कर रहा हूँ?

उत्तर

11

यह एक नामस्थान समस्या है। अभी:

var test = require("testMod"); // returns module.exports 
test.input = "Hello World"; // sets module.exports.input 
console.log(test.testFunc); // error, there is no module.exports.testFunc 

आप कर सकता है:

var test = require("testMod"); // returns module.exports 
test.test.input = "Hello World"; // sets module.exports.test.input 
console.log(test.test.testFunc); // returns function(){ return etc... } 

या, exports.test के बजाय आप module.exports = testModule तो कर सकता है,:

var test = require("testMod"); // returns module.exports (which is the Object testModule) 
test.input = "Hello World"; // sets module.exports.input 
console.log(test.testFunc); // returns function(){ return etc... } 
+0

बहुत बढ़िया धन्यवाद। – travega

संबंधित मुद्दे