Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does EventEmitter.call() do?

I saw this code sample:

function Dog(name) {     this.name = name;     EventEmitter.call(this); } 

it 'inherits' from EventEmitter, but what does the call() method actually do?

like image 434
Alexander Cogneau Avatar asked Feb 23 '13 12:02

Alexander Cogneau


People also ask

Which method will process the request parameters using on () method of EventEmitter class?

The on() method requires name of the event to handle and callback function which is called when an event is raised. The emit() function raises the specified event. First parameter is name of the event as a string and then arguments. An event can be emitted with zero or more arguments.

What does the node EventEmitter class on () method do?

All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter. on() function that allows one or more functions to be attached to named events emitted by the object.

What is the purpose of EventEmitter?

The EventEmitter is a module that facilitates communication/interaction between objects in Node. EventEmitter is at the core of Node asynchronous event-driven architecture. Many of Node's built-in modules inherit from EventEmitter including prominent frameworks like Express.


2 Answers

Basically, Dog is supposedly a constructor with a property name. The EventEmitter.call(this), when executed during Dog instance creation, appends properties declared from the EventEmitter constructor to Dog.

Remember: constructors are still functions, and can still be used as functions.

//An example EventEmitter function EventEmitter(){   //for example, if EventEmitter had these properties   //when EventEmitter.call(this) is executed in the Dog constructor   //it basically passes the new instance of Dog into this function as "this"   //where here, it appends properties to it   this.foo = 'foo';   this.bar = 'bar'; }  //And your constructor Dog function Dog(name) {     this.name = name;     //during instance creation, this line calls the EventEmitter function     //and passes "this" from this scope, which is your new instance of Dog     //as "this" in the EventEmitter constructor     EventEmitter.call(this); }  //create Dog var newDog = new Dog('furball'); //the name, from the Dog constructor newDog.name; //furball //foo and bar, which were appended to the instance by calling EventEmitter.call(this) newDog.foo; //foo newDoc.bar; //bar 
like image 161
Joseph Avatar answered Oct 05 '22 18:10

Joseph


EventEmitter.call(this); 

This line is roughly equivalent to calling super() in languages with classical inheritance.

like image 36
midhunsezhi Avatar answered Oct 05 '22 19:10

midhunsezhi