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
1 Answer
Reset to default 8You 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'))();