我看到這個代碼示例:EventEmitter.call()是做什麼的?
function Dog(name) {
this.name = name;
EventEmitter.call(this);
}
它繼承「從EventEmitter,但到底是什麼()的調用方法實際上呢?
我看到這個代碼示例:EventEmitter.call()是做什麼的?
function Dog(name) {
this.name = name;
EventEmitter.call(this);
}
它繼承「從EventEmitter,但到底是什麼()的調用方法實際上呢?
基本上,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
EventEmitter.call(this);
這條線是大致相當於調用語言超()與 經典的繼承。
添加一個註釋:以這種方式聲明函數'Dog'後,仍然調用:'util.inherits(Dog,EventEmitter)'來完成繼承。 – 2015-11-12 15:00:32