Javascript local static variable
It would be assigned every time the function is called. There are no static
variables in JavaScript. You need to declare them outside of the function. You can do that in a local scope, though:
var func;
{
const PARAMS = [
{"name": "from", "size": 160, "indexed": true},
{"name": "input", "size": 256, "indexed": false},
{"name": "output", "size": 256, "indexed": false},
];
func = function(data) {
…
}
}
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