26

我看到了这个代码示例:

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

它从 EventEmitter “继承”,但 call() 方法实际上做了什么?

4

2 回答 2

69

基本上,Dog应该是具有属性的构造函数name。在实例创建EventEmitter.call(this)期间执行时,将从构造函数Dog声明的属性附加到.EventEmitterDog

请记住:构造函数仍然是函数,并且仍然可以用作函数。

//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
于 2013-02-23T12:57:05.633 回答
27
EventEmitter.call(this);

这一行大致相当于在具有经典继承的语言中调用 super()。

于 2015-12-22T19:56:22.093 回答