最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS create new instance right upon import - Stack Overflow

programmeradmin4浏览0评论

I want to make an instance of a class without importing the class first and making new afterwards.

Instead of

var mainClass = require('../dist/main'); // has "class Main { ... }"
var mainInstance = new mainClass();

I want

var mainInstance = new require('../dist/main').Main();

But something with the syntax is wrong.

var main = new require('../dist/main').Main();
                                       ^
TypeError: Class constructor Main cannot be invoked without 'new'

Is this even possible? I use a bination of TypeScript and plain JS.

I want to make an instance of a class without importing the class first and making new afterwards.

Instead of

var mainClass = require('../dist/main'); // has "class Main { ... }"
var mainInstance = new mainClass();

I want

var mainInstance = new require('../dist/main').Main();

But something with the syntax is wrong.

var main = new require('../dist/main').Main();
                                       ^
TypeError: Class constructor Main cannot be invoked without 'new'

Is this even possible? I use a bination of TypeScript and plain JS.

Share Improve this question edited Jan 27, 2017 at 16:25 Daniel W. asked Jan 27, 2017 at 16:17 Daniel W.Daniel W. 32.4k15 gold badges99 silver badges155 bronze badges 3
  • What's the actual syntax error you get? – erbridge Commented Jan 27, 2017 at 16:23
  • @erbridge see my update – Daniel W. Commented Jan 27, 2017 at 16:25
  • If you want there to only ever be one instance, you could just export an instance instead of the class, to prevent misuse. – castletheperson Commented Jan 27, 2017 at 16:28
Add a ment  | 

1 Answer 1

Reset to default 8

You can use parenthesis to achieve that:

var main = new (require('../dist/main').Main)();

And if your module.exports was solely exporting a class you'd do it like following:

var main = new (require('../dist/main'))();
发布评论

评论列表(0)

  1. 暂无评论