Thursday 2 May 2019

scope - Javascript - Incrementing static function variable simulation with closures?



So it seems like there are no function static variables in Javascript. I am trying to increment a variable inside a function, but I do not want to do it like this:



function countMyself() {
if ( typeof countMyself.counter == 'undefined' ) {
// It has not... perform the initilization
countMyself.counter = 0;
}
}



I would like to do it with the closures, but I am having a really hard time to understand these.



Someone suggested this in another question:



var uniqueID = (function() {
var id = 0;
return function() { return id++; };
})();



But all it does when I alert uniqueID, is printing this line: return function() { return id++; };



So I would like to know how to increment a variable in a function without polluting the global scope.


Answer



You must actually call uniqueID - you can't just refer to is as if it were a variable:



> uniqueID
function () { return id++; }


> uniqueID()
0

> uniqueID()
1

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...