2011-05-04 4 views
2

메서드 내에서 이전 정수와 현재 정수를 비교해야합니다. 이게 효과가있는 것처럼 보이지만 그렇지 않습니다. 누군가가 문제가있는 곳을 말해 줄 수 있습니까? 현재는 메소드 외부에서 설정됩니다.JavaScript에서 메서드 내에서 이전 값을 추적하는 방법은 무엇입니까?

myMethod : function() { 
    var previous; 

    if (current > previous) { 
     // do this! 
    } 

    previous = current; 
} 
+0

어디에서 현재 정의되어 있습니까? "그럴 수 없다"는 것은 무엇을 의미합니까 –

답변

4

당신이 myMethod를 호출 할 때마다, previous은 (var previous) 새롭게 선언됩니다.

당신은 네 가지 가능성이 있습니다

(A) 폐쇄 만들기 (IMO 최적의 솔루션을하지만, 필요에 따라 다름) :

myMethod : (function() { 
    var previous = null; 
    return function() { 
     if (current > previous) { 
      // do this! 
     } 
     previous = current; 
    } 
}()); 

함수 객체의 속성으로 previous 설정 (B) :

myMethod : function() { 
    if (current > foo.myMethod.previous) { 
     // do this! 
    } 
    foo.myMethod.previous = current; 
} 

foo.myMethod.previous = null; 

그러나이 기능은 개체의 이름을 지정하는 데 매우 중요합니다.

(C)이 모델에 맞는 경우, 오브젝트 myMethod의 속성의 속성입니다 previous을 :

previous: null, 
myMethod : function() { 
    if (current > this.previous) { 
     // do this! 
    } 
    this.previous = current; 
} 

(D) (A)와 유사하게, 더 높은 어딘가에 외부 previous 설정 범위 :

var previous = null; 
// ... 
myMethod : function() { 

    if (current > previous) { 
     // do this! 
    } 
    previous = current; 
} 

이것은 상위 범위를 오염시키기 때문에 좋지 않습니다.

코드를 자세히 보지 않고도 알기가 어렵지만, current을 함수에 전달할 때 더 좋습니다.

+0

첫 번째 생각을 어떻게 활용할 수 있는지 예를 들려 줄 수 있습니까? – 1252748

0

상태를 유지하면됩니다.

var previousState = 'something'; 

function myMethod(current) 
{ 
    if(current > previousState) 
     // Do Something 

    previousState = current; 
} 
-1

메모 기능을 구현하려는 것 같습니다. 그것에 대해 갈 방법에 대한 좋은 자습서가 here 있습니다.

관련 문제