charliebrownie
charliebrownie

Reputation: 6097

Differences between this.prototype and module.exports?

As I am new to Node.js I am looking for some info, coding some testing stuff and also reading some other people's code.

I've seen that creating/requiring(using) modules is typical in Node.js. I've seen different ways of defining "public" methods and function inside modules and both seem to work the same way too:

Is there a notable difference by using one or another? Or are just different ways of doing the same thing? Is any of these two better, or it depends on the context?

Upvotes: 3

Views: 390

Answers (1)

mscdex
mscdex

Reputation: 106696

You should use either exports to attach properties to the predefined exported object or reassign module.exports to your own object. The latter is common when exporting a constructor for example.

exports.foo = function() { console.log('Hello world!'); };
exports.add = function(a, b) { return a + b; };

// Then the module might be used like so:
// var mymodule = require('./mymodule');
// mymodule.foo();
// console.log(mymodule.add(1, 9));

Or replace the exports object:

function Foo() {

}

module.exports = Foo;

// then typically users do this in their script:
// var Foo = require('./mymodule');
// var myFoo = new Foo();

Upvotes: 2

Related Questions