Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventEmitter creation

Tags:

node.js

What is the difference between following:

new require('events').EventEmitter();

AND

var events = require('events');
new events.EventEmitter();

The first one is not working, but second one - works.

Why?

like image 233
user1643318 Avatar asked Sep 28 '26 22:09

user1643318


1 Answers

Note the difference between these lines:

new foo().bar()

... and ...

new foo.bar()

In the first case new operator will change how foo() function is processed: it will be used as a constructor (with this pointing to its prototype copy etc.)

But in the second case new operator cannot be applied to foo, as the latter is not invoked: it's its bar property that is called instead. Naturally, new here means foo.bar is used as a constructor instead.

And that's exactly what happens in your example: the first case tries to apply new to require function call, not to %require_result%.EventEmitter one.

like image 110
raina77ow Avatar answered Sep 30 '26 10:09

raina77ow