Reputation: 1983
I am instantiating an event emitter and noticed that both of these lines seem to work fine.
Could anyone clarify tradeoffs or differences between these two ways to import and instantiate the EventEmitter class?
1: var eventEmitter = new (require('events')).EventEmitter();
2: var eventEmitter = new (require('events').EventEmitter)();
My take:
In 1, (require('events'))
should return the exports of the events
module. Then .EventEmitter()
references that class and new
create a new instance of EventEmitter
.
In 2, (require('events').EventEmitter) should return the exported EventEmitter class. Then
new...()creates a new instance of
EventEmitter`.
Upvotes: 1
Views: 200
Reputation: 1461
It is nothing unusual. You can put as many parentheses as you like around a function and then ()
after it and it will just work.
It's similar to
(1 + 2) === 3;
((1) + 2) === 3;
((1 + (2))) === (3);
etc... The same applies to objects/functions.
class MyClass { /* ... */ }
const object = {
c: MyClass,
};
let a = new object.c();
console.log(a === new (object).c());
console.log(a === new ((object.c))());
console.log(a === new ((object).c)());
etc...
It's worth noticing what you cannot put parenthese after a dot .
, so for example:
let a = new object.(c)();
would throw an error.
Upvotes: 1