2013-02-23 22 views
16

Ho visto questo esempio di codice:Che cosa fa EventEmitter.call()?

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

ne 'eredita' dal EventEmitter, ma ciò che fa il metodo call() in realtà lo fanno?

+1

Aggiungi una nota: dopo aver dichiarato la funzione 'Cane' in questo modo, ancora chiamiamo:' util.inherits (Dog, EventEmitter) 'per completare l'ereditarietà. –

risposta

52

Fondamentalmente, Dog è presumibilmente un costruttore con una proprietà name. Lo EventEmitter.call(this), se eseguito durante la creazione dell'istanza Dog, aggiunge le proprietà dichiarate dal costruttore EventEmitter a Dog.

Ricordare: i costruttori sono ancora funzioni e possono ancora essere utilizzati come funzioni.

//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 
+0

Oh, quindi è solo il costruttore di EventEmitter? Grazie per la tua risposta! –

+2

@AlexanderCogneau - Costruzione dell'EventEmitter sull'oggetto corrente - questo significa che il Cane restituito è sia un Cane che un EventEmitter. – Hogan

+0

@Joseph The Dreamer --- Bellissima risposta !, ha spiegato perfettamente. – Ben

17
EventEmitter.call(this); 

questa linea è più o meno equivalente a chiamare super() in lingue con eredità classica.