2012-01-26 6 views
9

Soy un novato de Nodes.js y estoy tratando de entender las construcciones de módulos. Hasta ahora tengo un módulo (testMod.js) define este constructo clase:Exportaciones de módulo clase Nodes.js

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

exports.test = testModule; 

intento para llamar al método TestFunc() así:

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

Pero consigo un TypeError:

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

¿Qué diablos estoy haciendo mal?

Respuesta

11

Es un problema de espacio de nombres. En este momento:

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 

que podría hacer:

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

O, en lugar de exports.test que podría hacer module.exports = testModule, entonces:

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

impresionante gracias. – travega

Cuestiones relacionadas