Answer the question
In order to leave comments, you need to log in
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';
};
module.exports = function () {
this.foo = 'baz';
};
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
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);
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;
}
var controllers = {};
controllers.user = require('./controllers/user')(); // обратите внимание на ()
controllers.account = require('./controllers/account')();
console.log(controllers.user()); // bar
console.log(controllers.account()); // baz
// user.js
module.exports = { foo: 'bar' };
var controllers = {};
controllers.user = require('./controllers/user');
controllers.account = require('./controllers/account');
console.log(controllers.user.foo); // bar
console.log(controllers.account.foo); // baz
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question