Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • module.exports
  • this.prototype

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?

like image 582
charliebrownie Avatar asked May 29 '26 10:05

charliebrownie


1 Answers

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();
like image 85
mscdex Avatar answered Jun 01 '26 00:06

mscdex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!