2012-01-26 8 views
9

Jestem noobem Nodes.js i staram się opanować konstrukcje modułów. Do tej pory mam moduł (testMod.js) zdefiniowane tej klasy konstrukt:Moduł eksportuje klasę Nodes.js

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

exports.test = testModule; 

próbuję wywołać metodę testFunc() wygląda następująco:

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

Ale otrzymuję TypeError:

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

Co robię źle robię?

Odpowiedz

11

Jest to problem z przestrzenią nazw. Teraz:

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 

Można zrobić:

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... } 

Albo zamiast exports.test można zrobić module.exports = testModule, a następnie:

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

Niesamowite dziękuję. – travega

Powiązane problemy