0

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

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 is not a function”。当我取消注释 changeState() 行时,它开始抱怨 EaselJS 库不正确(我知道这是正确的,因为它适用于我的其他项目)。有人可以帮我吗?它可能非常简单(就像往常一样),但我无法发现错误。如果你们愿意,我可以发布其余的代码,但我认为这无关紧要。

提前致谢!

4

1 回答 1

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;
    }
};
于 2013-04-09T20:53:22.433 回答