CNode

如何在构造函数中调用父方法?

问答
Sshaoyihe发布于11 年前最后回复11 年前3 回复3654 浏览0 收藏

我现在有个需求,是继承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)

W
William17#1·11 年前

参考

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();
S
shaoyihe#2·11 年前
引用 William17参考

@William17 确实是这样的

C
ChrisFuck#3·11 年前

参考call和apply,改变当前指向对象

参与回复
登录后即可参与回复。登录