What is the difference between:
var events = require('events'),
emitter = new events.EventEmitter();
and
var emitter = require('events').EventEmitter;
or EventEmitter
is pretty forgiving in using/not using new
and ()
?
What is the difference between:
var events = require('events'),
emitter = new events.EventEmitter();
and
var emitter = require('events').EventEmitter;
or EventEmitter
is pretty forgiving in using/not using new
and ()
?
Your second example doesn't call EventEmitter
at all. emitter
ends up being a reference to the function, not an object created by calling it.
If you meant to have ()
on that:
var events = require('events'),
emitter = new events.EventEmitter();
vs
var emitter = require('events').EventEmitter();
// Note ------------------------------------^^
Then there are two differences:
You have an events
object referring to the events module.
You didn't use new
when calling EventEmitter
.
If the resulting emitter
is identical, then yes, it means that EventEmitter
intentionally makes new
optional. I don't see that in the docs, so I don't know that I'd rely on it.
...or
EventEmitter
is pretty forgiving in using/not usingnew
and()
?
The last part of that suggests you've used a third option:
var emitter = new require('events').EventEmitter;
// `new` -----^ but no () --------------------^
Having ()
optional there isn't something EventEmitter
does; it's the JavaScript new
operator that's doing it: If you have no arguments to pass to the constructor function, the ()
are optional in a new
expression. new
always calls the function you give it, whether there are ()
there or not.
You can see the difference yourself,
var events = require('events'),
emitter = new events.EventEmitter();
console.log(typeof emitter);
// object
but when you do something like this
var emitter = require('events').EventEmitter;
console.log(typeof emitter);
// function
In the first case, you are invoking the EventEmitter
constructor function to get an object, but in the second case, you are simply making emitter
a reference to the EventEmitter
function itself.
As far as the new
part is concerned, it operates on a function object. Since you have no parameters to pass to EventEmitter
, the parenthesis is optional. But everywhere else, you need to use (...)
to execute the function.