Que fait EventEmitter.call ()?

J'ai vu cet exemple de code:

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

Il «hérite» de EventEmitter, mais qu'est-ce que la méthode call () fait effectivement?

Fondamentalement, Dog est censé être un constructeur avec un name propriété. L' EventEmitter.call(this) , lorsqu'il est exécuté pendant la création de l'instance Dog , ajoute les propriétés déclarées du constructeur EventEmitter à Dog .

Rappelez-vous: les constructeurs sont toujours des fonctions et peuvent encore être utilisés comme fonctions.

 //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 
 EventEmitter.call(this); 

Cette ligne est à peu près équivalente à appeler super () dans les langues avec héritage classique.