R
R
Ruslan Shashkov2014-01-14 14:00:04
Node.js
Ruslan Shashkov, 2014-01-14 14:00:04

Weird behavior of module.exports in NodeJS

How is it that the value of controllers.user.foo is overwritten by the value of controllers.account.foo?
./controllers/user.js

module.exports = function () {
    this.foo = 'bar';
};

./controllers/account.js
module.exports = function () {
    this.foo = 'baz';
};

app.js
var controllers = {};
controllers.user = require('./controllers/user');
controllers.account = require('./controllers/account');
console.log(controllers.user.foo) // baz

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kachok, 2014-01-14
@rshashkov

I'm not strong in javascript, but try this:

var controllers = {};
var User = require('./controllers/user');
var Account = require('./controllers/account');
controllers.user = new User();
controllers.account = new Account();
console.log(controllers.user.foo);

T
Timur Shemsedinov, 2014-01-14
@MarcusAurelius

That's right, this in your example does not refer to an object, but to module.exports. What are you trying to do?
Not the fact that it was necessary, the task is not clear, what should have been done? Depending on the task, you can replace this.variable = "value" with a closure:

// user.js
module.exports = function() {
  var foo = 'bar';
  var fn = function() {
    // тут будет доступно значение foo = 'bar'
    return foo;
  }
  return fn;
}

And account.js by analogy
Then you can call:
var controllers = {};
controllers.user = require('./controllers/user')(); // обратите внимание на ()
controllers.account = require('./controllers/account')();
console.log(controllers.user()); // bar
console.log(controllers.account()); // baz

Thus, there is no spawning of new objects, but variables are stored in closures and returned from there by functions.
Another option, more interesting for your case:
// user.js
module.exports = { foo:  'bar' };

And account.js by analogy
Then you can call:
var controllers = {};
controllers.user = require('./controllers/user');
controllers.account = require('./controllers/account');
console.log(controllers.user.foo); // bar
console.log(controllers.account.foo); // baz

But your code shows that you have not yet decided what user and account are - are they functions or prototypes? Are they controllers or models? I advise you not to use the words controller and model until you decide what it is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question