Static variable emulation

Keeping in mind that JavaScript considers functions just like specialized objects, it is easy to define something that acts like a C static variable.

As an example, let's see how we can implement and use a sequence generator:
sequence.value = 0; // 1
function sequence() {
    return sequence.value++; // 2
}

for(var i = 0; i < 3; ++i)
    console.log(sequence()); // 3
1. Define a property named value in the sequence function, initialized to zero. In this way we don't pollute the namespace in which the function is defined with a name that is used just by the function.
2. The current value is returned and then incremented.
3. Calling our function we get a new increased value each time.

This could be good enough in many case, but the fact that the internal status of the sequence function is visible and modifiable from anyone that sees the function itself could be sometimes worrisome.

A better solution, as we'll see soon, is to refactor our sequence function to become a closure.

No comments:

Post a Comment