2013-04-09 105 views
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; 
     } 
    }; 
} 

当我尝试运行它萤火显示此错误:“类型错误:that.changeState不是一个函数”在更新功能就行了。当我取消注释changeState()行时,它开始抱怨EaselJS库不正确(我知道这是正确的,因为它适用于我的其他项目)。有人可以帮助我吗?这可能很简单(就像往常一样),但我不能发现错误。如果你们喜欢,我可以发布其余的代码,但我认为它不相关。

在此先感谢!

+1

您是否试过从您的所有函数定义中删除'new'关键字... – searlea 2013-04-09 20:48:43

+0

如何创建一个新的状态机?它应该可以工作,如果你这样做:'var machine = new makeStateMachine();' – Bart 2013-04-09 20:48:54

回答

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; 
    } 
}; 
+0

这个技巧,以及其他一些修改我的脚本,因为它在不止一个地方被严重破坏。谢谢!但是,为什么要将这些功能添加到原型中?当你只是将它们作为变量添加到对象时,该对象是否不能正常工作?有没有一个动机,或者它只是一个整洁的编码风格? – bobismijnnaam 2013-04-09 22:18:55

+1

@bobismijnnaam - 将它们添加到原型时,该类的所有实例共享相同的代码。按照你这样做的方式,每个实例都有自己的函数副本 - 非常浪费。有一篇关于原型的好文章[这里](http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/)。 – 2013-04-09 22:25:38

+0

非常感谢! – bobismijnnaam 2013-04-10 05:48:37