Monday 5 December 2011

static variable in javascript

Functions are not primitive values in JavaScript, but a specialized kind of object, which means that functions can have properties. When a function needs a “static” variable whose value persists across invocations, it is often convenient to use a property of the function, instead of cluttering up the namespace by defining a global variable. You could store this information in a global variable, but that is unnecessary, because the information is used only by the function itself. It is better to store the information in a property of the Function object. So there're two solutions to solve this.
1) using global variable
2) function properties
function uniqueSuffix() {
    uniqueSuffix.counter = uniqueSuffix.counter || 0;
    return uniqueSuffix.counter++;
}

uniqueSuffix();
uniqueSuffix();
console.log(uniqueSuffix.counter); // >>2

No comments:

Post a Comment