Not sure I completely understand answers to similar questions that I found here, so trying to be absolutely sure:
I would like to have a local variable in a function, initialized only once (similar to static variables in strongly-typed languages such as C, C++, etc).
Of course, I could declare it globally, but it seems better practice to have it within the scope of that function, since it is not used anywhere else.
Now, here is what I do:
function func(data) {
func.PARAMS = [
{"name": "from", "size": 160, "indexed": true},
{"name": "input", "size": 256, "indexed": false},
{"name": "output", "size": 256, "indexed": false},
];
...
}
And my question is, will func.PARAMS
indeed be initialized only once, or will it be initialized every time the function is called?
According to some of the answers that I found (this one for example), I need to precede the initialization with something like:
if (typeof func.PARAMS == 'undefined')
This "supplemental" would be irrelevant in strongly-typed languages of course, so I just want to be sure that it is absolutely necessary in order to ensure "static behavior" (i.e., one-time initialization).
In addition to using properties of the function object, as you do in your example, there are 3 other ways to emulate function-local static variables in Javascript.
All of them rely on a closure, but using different syntax.
Method 1 (supported in old browsers):
var someFunc1 = (function(){
var staticVar = 0 ;
return function(){
alert(++staticVar) ;
}
})() ;
someFunc1() ; //prints 1
someFunc1() ; //prints 2
someFunc1() ; //prints 3
Method 2 (also supported in old browsers):
var someFunc2 ;
with({staticVar:0})
var someFunc2 = function(){
alert(++staticVar) ;
} ;
someFunc2() ; //prints 1
someFunc2() ; //prints 2
someFunc2() ; //prints 3
Method 3 (requires support for EcmaScript 2015):
{
let staticVar = 0 ;
function someFunc3(){
alert(++staticVar) ;
}
}
someFunc3() ; //prints 1
someFunc3() ; //prints 2
someFunc3() ; //prints 3
Method 3 for strict mode:
'use strict'
{
let staticVar = 0 ;
var someFunc3 = function(){
alert(++staticVar) ;
} ;
}
someFunc3() ; //prints 1
someFunc3() ; //prints 2
someFunc3() ; //prints 3