मैं इस कोड का नमूना देखा:EventEmitter.call() क्या करता है?
function Dog(name) {
this.name = name;
EventEmitter.call(this);
}
यह inherits 'EventEmitter से, लेकिन कॉल() विधि वास्तव में क्या करता है?
मैं इस कोड का नमूना देखा:EventEmitter.call() क्या करता है?
function Dog(name) {
this.name = name;
EventEmitter.call(this);
}
यह inherits 'EventEmitter से, लेकिन कॉल() विधि वास्तव में क्या करता है?
असल में, 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
EventEmitter.call(this);
इस लाइन मोटे तौर पर शास्त्रीय विरासत के साथ भाषाओं में सुपर() कॉल के बराबर है।
एक नोट जोड़ें: फ़ंक्शन 'कुत्ते' को इस तरह घोषित करने के बाद, हम अभी भी कॉल करते हैं: 'util.inherits (कुत्ता, EventEmitter) 'विरासत को समाप्त करने के लिए। –