Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

javascript - Pattern or best way to construct new objects from required module?

I've broken my code up into a number of Typescript classes and interfaces, and while it works well and is great for testing and maintenance, I'm wondering if there's a better way to construct required objects. As far as I know, my choices are to require and construct like so:

const MyModule = require('./src/mymodule');
const myModule = new MyModule();

or

const myModule = new (require('./src/mymodule'))();

Is there another solution or pattern as an alternative that might make this more readable/clean?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...