In my opinion, there exists a subtle distinction, but one that may not have much impact in this specific scenario.
When utilizing the require
statement in Node.js
, what you ultimately receive is the object that the module assigns to module.exports
. This could be anything from a simple value to a function.
For example, consider having the following module defined in myModule.js
:
function complexOperation() {
// code here
}
module.exports = complexOperation;
Upon executing:
var myModule = require("myModule.js");
You will have myModule
set to complexOperation
, which can then be called like a regular function. It's straightforward. However, using new complexOperation()
may not always be appropriate depending on what complexOperation
does.
In the case of Express.js
, the returned object itself is a function called
createApplication</code (defined here: <a href="https://github.com/strongloop/express/blob/master/lib/express.js" rel="nofollow">https://github.com/strongloop/express/blob/master/lib/express.js</a>). Therefore, <code>require('express')
returns a function assigned to
express</code, which is then executed on the next line resulting in <code>app
holding the output of
createApplication
.
The second approach involves using the new
keyword, where:
var a = new Something();
Something
should be a constructor function. This statement creates a new object, calls Something()
with this
referring to the new object, and returns the outcome of Something()
.
In the given context, var app = new Express()
generates a fresh object, invokes Express()
with this
linked to the newly created object, and then stores the result.
In the context of Express.js
, since the exported item is a function, a similar outcome ensues. A new object is generated, createApplication
is executed with proper setup, and then app
obtains the result of createApplication
.