1

I created a module like this:

module.exports = function foo(){
    this.run = function ()
    {
        console.log("run");
    }
}

now i want to require the module in an node.js application and immediatly get an instance. I tried to get it in a simple line, but it doesn't work. The code looks like this:

var foo = new require('./foo.js')();
foo.run();

foo will be undefined and therefore run cannot be raised.

First working Solution:

var foo = require('./foo.js');

var instance = new foo();
instance.run();

console.log('Hello world');

Second working Solution (as i understand adeneo)

function foo() {
    this.run = function () {
        console.log("run");
    }
}

module.exports = new foo();

Which solution is more common ? are there more?

Boas Enkler
  • 12,264
  • 16
  • 69
  • 143
  • 1
    http://stackoverflow.com/questions/20787074/what-is-the-difference-between-require-and-new-require – adeneo Feb 01 '15 at 13:48
  • ok that explains why it doesn't work. but i can't see what an apporpiate way would be to class like components in my node application. Is it like i pointed out in the second code ? is there a better way? – Boas Enkler Feb 01 '15 at 13:50
  • Generally you wouldn't use class-like modules, and if you do you'd return an instance directly or store the exported function in a variable, there's no need to call `new` directly on require – adeneo Feb 01 '15 at 13:52
  • so i would create an instance of the class and attach it instead to the export ? like export = new foo() ? – Boas Enkler Feb 01 '15 at 13:54
  • That depends, why do you need an instance, and why are you using prototypes, if only to get one single new instance when you import the middleware ? – adeneo Feb 01 '15 at 13:58
  • I want to build a rich domain model. is there a better apporach ? – Boas Enkler Feb 01 '15 at 14:00

0 Answers0