2013-02-23 11 views
16

मैं इस कोड का नमूना देखा:EventEmitter.call() क्या करता है?

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

यह inherits 'EventEmitter से, लेकिन कॉल() विधि वास्तव में क्या करता है?

+1

एक नोट जोड़ें: फ़ंक्शन 'कुत्ते' को इस तरह घोषित करने के बाद, हम अभी भी कॉल करते हैं: 'util.inherits (कुत्ता, EventEmitter) 'विरासत को समाप्त करने के लिए। –

उत्तर

52

असल में, Dog माना जाता है कि एक संपत्ति name के साथ एक निर्माता है। EventEmitter.call(this), जब Dog उदाहरण निर्माण के दौरान निष्पादित किया गया, EventEmitter कन्स्ट्रक्टर से Dog पर घोषित गुणों को जोड़ता है।

याद रखें: निर्माता अभी भी कार्य कर रहे हैं, और अभी भी फ़ंक्शंस के रूप में उपयोग किए जा सकते हैं।

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

ओह, तो यह सिर्फ EventEmitter का निर्माता है? आपके उत्तर के लिए धन्यवाद! –

+2

@AlexanderCogneau - वर्तमान ऑब्जेक्ट पर EventEmitter का निर्माण - इसका मतलब है कि लौटा हुआ कुत्ता एक कुत्ता और इवेंटइमीटर दोनों है। – Hogan

+0

@ जोसेफ द ड्रीमर --- सुंदर उत्तर !, पूरी तरह से समझाया गया। – Ben

17
EventEmitter.call(this); 

इस लाइन मोटे तौर पर शास्त्रीय विरासत के साथ भाषाओं में सुपर() कॉल के बराबर है।

संबंधित मुद्दे