Nam Nguyen
Nam Nguyen

Reputation: 5750

Differences between three different ways using module.exports

I saw some people use different ways to create a class but I really don't know the differences or advantage using inline, use name or without function name. For example:

// Style 1. myclass.js. Use module.exports on a var
var myClass = function MyClass() {
   return something;
};

module.exports = myClass;

// Style 2. myclass.js. inline module.exports
module.exports = function MyClass() {
  return something;
};

// Style 3. myclass.js. inline module.export without function name
module.exports = function () {
   return something;
};

Usage:

var MyClass = require('myclass');
var classObj = new MyClass();

can anyone please explain or tell me the differences? I guess that using with function name will give much more info on stack trace?

Thanks

Upvotes: 0

Views: 364

Answers (1)

Nitzan Shaked
Nitzan Shaked

Reputation: 13598

Differences are small.

The difference between #1 and #2 is that myClass (the variable) can be used in other places within the module.

The difference between #2 and #3 is that the function has a name, and thus:

  1. It is easier to use recursion if you want to (though not impossible in #3)
  2. You get nicer-looking stack trace, as you said.

(Constructors are sometimes recursive, with the idiom that you can call them both with and without new, and they first check whether this is an instance of MyClass and if not call themselves recursively with new).

Upvotes: 3

Related Questions