1

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 ()?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nik Terentyev
  • 2,270
  • 3
  • 16
  • 23
  • related: https://stackoverflow.com/questions/17604497/how-does-require-work-with-new-operator-in-node-js – Bergi Dec 02 '20 at 15:47

2 Answers2

4

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:

  1. You have an events object referring to the events module.

  2. 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 using new 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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497