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?
Solution 1:
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 EventEmitterfunctionEventEmitter(){
//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 itthis.foo = 'foo';
this.bar = 'bar';
}
//And your constructor DogfunctionDog(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 constructorEventEmitter.call(this);
}
//create Dogvar newDog = newDog('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
Post a Comment for "What Does Eventemitter.call() Do?"