function Dog(name) {
this.name = name;
EventEmitter.call(this);
}
он наследует от EventEmitter, но что делает метод call()?
Ответ 1
В принципе, 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
Ответ 2
EventEmitter.call(this);
Эта строка примерно эквивалентна вызову super() на языках с
классическое наследование.