Learn Node.JS | module.exports and require() - clarifications

link to lesson

I was wondering why/when we would want to assign module.exports to a Class function instead of an Object in Node.

In the specified lesson we have this example:

However we know from the Node documentation that the module object is the following:

Module {
  id: '.',
  path: '/absolute/path/to',
  exports: {},
  filename: '/absolute/path/to/entry.js',
  loaded: false,
  children: [],
  paths:
   [ '/absolute/path/to/node_modules',
     '/absolute/path/node_modules',
     '/absolute/node_modules',
     '/node_modules' ] }

So exports is initialized as an empty Object. But in the docs about module.exports is also stated:

The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class.

Who are those many? Why they want that? Can anybody provide some examples?

Cheers,

We would either use a factory function or a Class when we want to create new instances of the code we’re exporting/importing through modules.

In the case of the exercise in app.js we would import two different Classes (Cat and Dog) and we would later create two different instances of the Classes (one instance for each Class).

We could also do that with objects but the code would be about 3 times more.

Hopefully this will be helpful to someone else having my same confusion :slight_smile:

1 Like