If you need to create multiple objects within a given module, then you would use your first scheme where you save the module handle to a local variable first so you can reference it multiple times:
const SomeConstructor = require('./src/mymodule');
const myObj1 = new SomeConstructor();
const myObj2 = new SomeConstructor();
If you only need to create one object of that type within a given module and there are no other exports from that module that you need in this module, then as you have shown you don't need to store the constructor/module handle in its own variable first so you can just use it directly as you've shown:
const myObj = new (require('./src/mymodule'))();
Because this syntax looks slightly awkward, it is common to export a factory function that automatically applies new
for you. For example, the http
module exposes a factory function to create a server:
const http = require('http');
const server = http.createServer(...);
In your example, you could do either one of these:
// module constructor is a factory function for creating new objects
const myObj = require('./src/mymodule')();
// module exports a factory function for creating new objects
const myObj = require('./src/mymodule').createObj();
An example in the Express server framework is this:
const app = require('express')();
Of, if you want to access other exports from the express module:
const express = require('express');
const app = express();
app.use(express.static('public'));
In the Express example, it exports both a factory function and other methods that are properties on the factory function. You can choose to use only the factory function (first example above) or you can save the factory function so you can also access some of the properties on it (second example).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…