Ad

JS Increment Variable If Exists, Else Create New

- 1 answer

I wanted to create a local function variable for a specific use case without polluting my global object scope. I will be calling doThis() multiple times, but want to keep the local counter value.

So, do this:

TaskHandler = {

     doThis : function () { 
            myVariable+= (myVariable) ? var myVariable = 0;
            doSomethingWithVariable(myVariable);

            // OR

            var myVariable = myVariable+=1 || 0;

            // OR

            var myVariable = (myVariable) ? myVariable+=1 : 0;
     }

Instead of:

TaskHandler = {
     myVariable : 0,

     doThis : function () { 
            this.myVariable++;
            doSomethingWithVariable(this.myVariable);
     }

Is this possible?


TaskHandler = {

    doThis : function (requirement) {

        var track_index = (function () {
           var myVariable = 0;
           return function () {
               ++myVariable;
           }
        })();

       doSomethingWithVariable(track_index);
   },

}

    TaskHandler = {

        doThis : function () {

         (function () {
            console.log('called'); // This is called
            var myVariable = 0;
            return function () {
                ++myVariable;
                console.log(myVariable); // This is NOT called
            }
        })();
   }
}

Last edit:

TaskHandler = {

    someFunction : function (myObject) {

        this.doThis(myObject).counter();
    },

    doThis : function (myObject) {

         return {
            counter : (function (myObject) {
                var myVariable = 0;
                return function () {
                    ++myVariable;
                    console.log('index', myVariable); //not incrementing
                }
            })(myObject)
        }
    }
}
Ad

Answer

You need a closure: a function that is declared within a scope of a local variable, and that therefore "remembers" this variable later on.

For example:

TaskHandler = {

    doThis : (function () {
        var myVariable = -1;

        return function () {
            ++myVariable;
            doSomethingWithVariable(myVariable);
        };
    })(),

    // ... rest of TaskHandler's properties ...
 }

(where (function () { ... })() is an immediately-invoked function expression).

Ad
source: stackoverflow.com
Ad