对象不能找到方法

Object can't find method

本文关键字:方法 不能 对象      更新时间:2023-09-26

我试图使一个状态机,但它不工作。到目前为止,我已经得到了以下代码:

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库不正确(我知道这是正确的,因为它适用于我的其他项目)。有人能帮我一下吗?它可能是一些非常简单的东西(就像往常一样),但我就是找不到错误。如果你们喜欢的话,我可以把剩下的代码贴出来,但我认为这是不相关的。

提前感谢!

您应该将这些函数放在原型中。你也不应该使用= 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;
    }
};