2

Simple example:

file1

module.exports.foo = function(obj) {
  module.exports.obj = obj;
}

file2

file1 = require("file1")
var something = {a: "a"};
file1.foo(something); //export "something" being a part of file2

The example above is not working.

What I want is basically a module.exports helper, since I plan a few helpers for whole object "exportion".

Thank you

eSinxoll
  • 407
  • 1
  • 6
  • 15
  • What error, you are getting ? – Riz Oct 01 '12 at 12:11
  • 1
    The code you have posted works exactly as you seem to expect. Test case: `var f2 = require('./file2'); var f1 = require('./file1'); console.log(f1.obj);` outputs `{ a: 'a' }`. – lanzz Oct 01 '12 at 12:13
  • When I try to access the "file2" module from a third file, the "file2" module is empty. I want to export objects from file2, but the act of export is happning in a function inside file1. – eSinxoll Oct 01 '12 at 12:27
  • Why don't you just `return obj;` in the `foo` function? – jwchang Oct 01 '12 at 14:06

1 Answers1

1

module in file1.js is a different instance from that in file2.js.

file1.js

module.exports.foo = function(obj) {
    module.exports.obj = obj; 
    return module;
}  

file2.js

console.log("running file2");

file1 = require("./file1");

var something = {a: "a"}; 
var moduleOfFile1 = file1.foo(something); //export "something" being a part of file2 

console.log("file1 module: " + moduleOfFile1.id);
console.log("file2 module: " + module.id);

console:

node file2.js

id returned are different


Update

alternatively, why not update file2.js to extend its module.exports

File2.js

// well, you may copy `extend` implementation if you 
// do not want to depend on `underscore.js`
var _ = require("underscore");     
file1 = require("./file1");  

_.extend(module.exports, file1);

var something = {a: "a"};  
// or do something else

_.extend(module.exports, {
    obj: something
});

File3.js

file2 = require("./file2.js");
console.log(file2.obj.a);
OnesimusUnbound
  • 2,886
  • 3
  • 30
  • 40
  • Another question: why is "this" an empty object outside a function? I though the "module.exports" would belong to "this". – eSinxoll Oct 01 '12 at 23:04
  • 1
    [This](http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal) may help you understand the confusing `this` in JavaScript. In summary, the value of `this` depends on where it's accessed. – OnesimusUnbound Oct 02 '12 at 06:30