如果需要在给定的模块中创建多个对象,则可以使用第一个方案,首先将模块句柄保存到局部变量,以便可以多次引用它:
const SomeConstructor = require('./src/mymodule');const myObj1 = new SomeConstructor();const myObj2 = new SomeConstructor();如果您只需要在给定的模块中创建一个该类型的对象,并且在该模块中不需要该模块的其他导出,则如您所显示的,您不需要在其模块中存储构造函数/模块句柄首先拥有变量,因此您可以直接使用它,如下所示:
const myObj = new (require('./src/mymodule'))();由于此语法看起来有些尴尬,通常会 导出自动适用new
于您的工厂函数。例如,该
http模块公开了一个工厂函数来创建服务器:
const http = require('http');const server = http.createServer(...);在您的示例中,您可以执行以下任一操作:
// module constructor is a factory function for creating new objectsconst myObj = require('./src/mymodule')();// module exports a factory function for creating new objectsconst myObj = require('./src/mymodule').createObj();Express服务器框架中的一个示例是这样的:
const app = require('express')();其中,如果要从express模块访问其他导出,请执行以下操作:
const express = require('express');const app = express();app.use(express.static('public'));在Express示例中,它同时导出工厂功能和作为工厂功能属性的其他方法。您可以选择仅使用工厂功能(上面的第一个示例),也可以保存工厂功能,以便还可以访问其上的某些属性(第二个示例)。



