2013-04-09 109 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