CreateJS EventDispatcher和继承

时间:2014-01-09 06:44:01

标签: javascript inheritance event-handling createjs

我正在尝试创建一个具有createjs EventDispatcher功能的基类,然后从这个基类创建子类,但如果我尝试在子类实例上使用addEventListener,我会收到错误:

TypeError: _subClass.addEventListener is not a function

我的类的构造函数如下所示:

var BaseClass = function(id)
{
    _instance = this;
    _id = id;
    createjs.EventDispatcher.initialize(BaseClass.prototype);
};

var SubClass = function(id)
{
    BaseClass.call(this, id);
    SubClass.prototype = Object.create(BaseClass.prototype);
    _instance = this;
};

如何让它工作以便SubClass从BaseClass继承应用的CreateJS事件调度程序功能?到目前为止它只有在我也在子类构造函数中应用事件调度程序时才有效,但是它在某种程度上违背了继承的整个目的:

createjs.EventDispatcher.initialize(SubClass.prototype);

1 个答案:

答案 0 :(得分:0)

您应该在初始化期间初始化原型,而不是在构造函数中初始化。这是一个更新的小提琴:http://jsfiddle.net/lannymcnie/qTHb4/

var BaseClass = function(id)
{
    _instance = this;
    _id = id;
};
createjs.EventDispatcher.initialize(BaseClass.prototype);

var SubClass = function(id)
{
    BaseClass.call(this, id);
    _instance = this;
};
SubClass.prototype = BaseClass.prototype;