如何在构造函数中调用父方法?
我现在有个需求,是继承EventEmitter
,但是我需要调用他的On方法,自然放到其构造函数中肯定更好,但是不知道如何实现?
var events = require("events");
function LoopEvents(childCount, parent){
this.childCount = childCount || 0;
//???
}
//这里实现继承
util.inherits(LoopEvents, events.EventEmitter);
function newLoopEvents(){
var loopEvents = new LoopEvents();
//我如何把这段代码放到LoopEvents构造函数中?这样明显每次构造LoopEvents很麻烦。
loopEvents.on("childDone", function(){
++this.hadDoneChildCount ;
if (this.hadDoneChildCount == this.childCount) {
this.emit("childAllDone");
}
});
return loopEvents;
}
var root = newLoopEvents();
3 回复
参考
var util = require('util');
var EventEmitter = require("events");
function LoopEvents(childCount, parent) {
EventEmitter.call(this);
this.childCount = childCount || 0;
this.on("childDone", function(){
++this.hadDoneChildCount;
if (this.hadDoneChildCount == this.childCount) {
this.emit("childAllDone");
}
});
}
util.inherits(LoopEvents, EventEmitter);
var root = new LoopEvents();
@William17 确实是这样的
参考call和apply,改变当前指向对象