Jos de Jong
Jos de Jong

Reputation: 6819

Exporting a prototype in node.js: module.exports=Prototype or exports.Prototype=Prototype?

What is the preferred way to export a prototype in node.js? You can take two approaches:

  1. Export the prototype itself

    function A () {
    }
    module.exports = A;
    

    which is used as:

    var A = require('./A.js');
    var a = new A();
    
  2. Export an object containing the prototype as property

    function A () {
    }
    exports.A = A;
    

    which is used as:

    var A = require('./A.js').A;
    var p = new A();
    

The first solution looks much more convenient to me, though I know there are concerns about replacing the exports object. Which of the two is best to use and why?

Upvotes: 7

Views: 4953

Answers (1)

Esailija
Esailija

Reputation: 140228

The second one would only be useful if you exported multiple classes from one file which is something that is questionable by itself.

There is no problem in replacing the exports object at all.

Upvotes: 3

Related Questions