You get a bonus - 1 coin for daily activity. Now you have 1 coin

Static variables

Lecture




  1. Use circuit
  2. Writing properties to a function

A static variable of a function is one that stores the value between calls.

Such variables are in many languages. In JavaScript, they are not implemented syntactically, but an analogue can be organized.

Use circuit

In the previous chapter, we saw how to implement a static variable using a closure.

In the example below, the count of the sayHi function sayHi stored in a wrapper:

01 var sayHi = ( function () {
02
03    var count = 0; // статическая переменная
04
05    return function () {
06      count++;
07
08      alert( "Привет " + count);
09    };
10
11 })();
12
13 sayHi(); // Привет 1
14 sayHi(); // Привет 2

This is a pretty good way, but, as an alternative, consider another one.

Writing properties to a function

Due to the fact that a function is an object, you can add static properties directly to it.

Rewrite the example using the function entry:

01 function sayHi() {
02    sayHi.count++;
03
04    alert( "Привет " + sayHi.count);
05 }
06
07 sayHi.count = 0; // начальное значение
08
09 sayHi(); // Привет 1
10 sayHi(); // Привет 2

As you can see, the example works the same, but inside everything is different.

A static variable written as a property of a function is publicly available. Anyone who has a function object has access to it.

This is different from binding through closure.

Importance: 3

Create a counter that uses a static variable to store currentCount instead of a closure.

Counter code, working through the circuit (for rework):

1 function makeCounter() {
2    // currentCount можно считать "статической переменной" счётчика
3    var currentCount = 0;
4
5    return function () {
6      currentCount++;
7      return currentCount;
8    };
9 }

Important: the counters must be independent:

1 var c1 = makeCounter();
2 var c2 = makeCounter();
3
4 alert( c1() ); // 1
5 alert( c2() ); // 1
6 alert( c1() ); // 2

Decision

Rewritten counter:

01 function makeCounter() {
02    return function f() {
03      if (!f.currentCount) {
04        f.currentCount = 0;
05      }
06
07      return ++f.currentCount;
08    };
09 }
10
11 var c1 = makeCounter();
12 var c2 = makeCounter();
13
14 alert( c1() ); // 1
15 alert( c2() ); // 1
16 alert( c1() ); // 2

A side effect - the current value of the counter is now available outside through the property of the function:

1 var counter = makeCounter();
2
3 counter();
4 alert( counter.currentCount ); // 1

created: 2014-10-07
updated: 2024-11-14
416



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone