📜 ⬆️ ⬇️

Imitation of static variables in JavaSctipt

Static variables are variables that retain their value between function calls. Javascript does not support static variables and there is no static keyword .
But since functions in javascript are also objects, we can simulate static variables. All that needs to be done is to create a variable that will be a member of the function and a part of the object, respectively, and its value will then be saved between calls.

Here is a simple example:

function counterFunction() {
//
if ( typeof (counterFunction.counter) == 'undefined' ) {
//
counterFunction.counter = 0;
}

//
alert(++counterFunction.counter);
}

')

Source: https://habr.com/ru/post/69825/


All Articles