Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 : function() {
    var previous;

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

    previous = current;
}
like image 444
Cofey Avatar asked Oct 18 '25 19:10

Cofey


2 Answers

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.

like image 146
Felix Kling Avatar answered Oct 20 '25 08:10

Felix Kling


You just need to maintain state.

var previousState = 'something';

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

    previousState = current;
}
like image 42
Tejs Avatar answered Oct 20 '25 08:10

Tejs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!