开发者

How to keep track of a previous value within a method in JavaScript?

I need to compare a current integer with a previous integar within a method. It seems like something like this should work, but it doesn't. Can someone tell me where the problem lies? Note current is set outside the method.

myMethod 开发者_StackOverflow社区: function() {
    var previous;

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

    previous = current;
}


Every time you call myMethod, previous is declared anew (var previous).

You have four possibilities:

(A) Create a closure (best solution imo, but depends on your needs):

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

(B) Set previous as property of the function object:

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

foo.myMethod.previous = null;

But this ties the function very much to the naming of the object.

(C) If it fits in your model, make previous a property of the object myMethod is a property of:

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

(D) Similar to (A), set previous somewhere outside in a higher scope:

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

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

This is not a good imo as it pollutes the higher scope.

Without seeing more of your code it is hard to tell, but it is probably also better when you pass current to the function.


You just need to maintain state.

var previousState = 'something';

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

    previousState = current;
}


Seems like you are trying to implement a memoization function. There is a good tutorial on how to go about it here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜