2013-02-23 101 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); 

這條線是大致相當於調用語言超()與 經典的繼承。