2013-02-23 134 views
16

我看到这个代码示例:EventEmitter.call()是做什么的?

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

它继承“从EventEmitter,但到底是什么()的调用方法实际上呢?

+1

添加一个注释:以这种方式声明函数'Dog'后,仍然调用:'util.inherits(Dog,EventEmitter)'来完成继承。 – 2015-11-12 15:00:32

回答

52

基本上,Dog应该是一个属性为name的构造函数。在Dog实例创建期间执行时,EventEmitter.call(this)将从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的构造器?感谢您的回答! – 2013-02-23 12:59:45

+2

@AlexanderCogneau - 在当前对象上构建EventEmitter - 这意味着返回的Dog既是狗也是EventEmitter。 – Hogan 2013-02-24 03:25:04

+0

@Joseph梦想家---美丽的回答!完美地解释。 – Ben 2015-05-27 19:37:50

17
EventEmitter.call(this); 

这条线是大致相当于调用语言超()与 经典的继承。