Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - Creating instance of a class directly from require

I have a class in a seperate file. I need to create an instance of it in another file. I tried this:

var connection = new require('./connection.js')("ef66143e996d");

But this is not working as I wanted. Right now I am using this as a temporary solution:

var Connection = require('./connection.js'); 
connection = new Connection("ef66143e996d");

Two Questions;

First, why doesn't that work.
Second, how can I accomplish this with a one-liner?

like image 403
DifferentPseudonym Avatar asked Nov 19 '15 17:11

DifferentPseudonym


1 Answers

The new keyword applies itself on the first function it comes across. In this case, that happens to be require. Wrapping the statement in parentheses will expose the correct function:

var connection = new (require('./connection.js'))("ef66143e996d");
like image 105
jperezov Avatar answered Oct 26 '22 05:10

jperezov