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

+0

새 상태 시스템은 어떻게 작성합니까? 'var machine = new makeStateMachine();' – Bart

답변

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

+1

@bobismijnnaam - 프로토 타입에 추가하면 클래스의 모든 인스턴스가 동일한 코드를 공유합니다. 당신이 그것을하는 방식으로, 각 인스턴스는 기능의 복사본을 가지고 있습니다 - 매우 낭비입니다. 프로토 타입 [여기] (http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/)에 대한 멋진 기사가 있습니다. –

+0

대단히 고마워요! – bobismijnnaam

관련 문제