对象无法找到方法

时间:2013-04-09 20:46:59

标签: javascript html5 state-machine easeljs

我正在尝试创建状态机,但它没有成功。到目前为止我已经有了这段代码:

function makeStateMachine() {
    this.stateConstructors = new Object();
    this.currState = {
        update : function(e) {
            // Nothing to do here
        },
        exit : function() {
            // Nothing to declare
        }
    };
    this.nextState = null;

    var that = this;

    this.update = new function(e) {
        that.currState.update(e);

        that.changeState();
    };

    this.setNextState = new function(targetState) {
        that.nextState = targetState;
    };

    this.addState = new function(constructor, stateName) {
        that.stateConstructors[stateName] = constructor;
    };

    this.changeState = new function() {
        if (that.nextState != null) {
            that.currState.exit();
            that.currState = new that.stateConstructors[that.nextState]();

            that.nextState = null;
        }
    };
}

当我尝试运行它时,firebug会在更新函数的行中显示以下错误:“TypeError:that.changeState不是函数”。当我取消注释changeState()行时,它开始抱怨EaselJS库不正确(我知道这是正确的,因为它适用于我的其他项目)。有人可以帮帮我吗?它可能非常简单(就像一直),但我无法发现错误。如果你们愿意,我可以发布剩下的代码,但我认为它不相关。

提前致谢!

1 个答案:

答案 0 :(得分:0)

您应该将这些功能放在原型中。你也不应该使用= new function(...;只需使用= function(...。最后,您不需要that。试试这段代码:

function makeStateMachine() {
    this.stateConstructors = {};
    this.currState = {
        update : function(e) {
            // Nothing to do here
        },
        exit : function() {
            // Nothing to declare
        }
    };
    this.nextState = null;
}

makeStateMachine.prototype.update = function(e) {
    this.currState.update(e);
    this.changeState();
};

makeStateMachine.prototype.setNextState = function(targetState) {
    this.nextState = targetState;
};

makeStateMachine.prototype.addState = function(constructor, stateName) {
    this.stateConstructors[stateName] = constructor;
};

makeStateMachine.prototype.changeState = function() {
    if (this.nextState != null) {
        this.currState.exit();
        this.currState = new this.stateConstructors[this.nextState]();
        this.nextState = null;
    }
};