Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...