私はこのコードサンプルを見ました:
function Dog(name) {
this.name = name;
EventEmitter.call(this);
}
EventEmitterから「継承」しますが、call()メソッドは実際に何をしますか?
私はこのコードサンプルを見ました:
function Dog(name) {
this.name = name;
EventEmitter.call(this);
}
EventEmitterから「継承」しますが、call()メソッドは実際に何をしますか?
基本的に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
EventEmitter.call(this);
この行は、古典的な継承を持つ言語でsuper()を呼び出すのとほぼ同じです。