Javascript 对象可以';找不到方法
我正试图制造一个状态机,但没有成功。到目前为止,我得到了以下代码:Javascript 对象可以';找不到方法,javascript,html,state-machine,easeljs,Javascript,Html,State Machine,Easeljs,我正试图制造一个状态机,但没有成功。到目前为止,我得到了以下代码: function makeStateMachine() { this.stateConstructors = new Object(); this.currState = { update : function(e) { // Nothing to do here }, exit : function() { // N
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(…
)。最后,您不需要使用即。请尝试以下代码:
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;
}
};
您是否尝试过从所有函数定义中删除new
关键字…如何创建新的状态机?如果您这样做,它应该可以工作:var machine=new makeStateMachine()
这就成功了,同时对我的脚本的其余部分进行了一些其他修改,因为它在不止一个地方被严重破坏。谢谢!但是,为什么要将函数添加到原型中?当你只是将它们作为变量添加到对象中时,对象不是也工作得很好吗?是有动机还是只是一个更简洁的密码g style?@bobismijnnaam-当您将它们添加到原型中时,该类的所有实例共享相同的代码。按照您的方式,每个实例都有自己的函数副本——非常浪费。有一篇关于原型的好文章。