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)
}
}
}