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:
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:
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
Rewritten counter:
A side effect - the current value of the counter is now available outside through the property of the function:
1 | var counter = makeCounter(); |
4 | alert( counter.currentCount ); |
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone