Whilst reading the Javascript: The Definitive Guide I was intrigued by the section Defining Your Own Function Properties. Let me give you an example:
function foo( ) {
foo.bar++;
return foo.bar;
};
foo.bar = 0;
foo( ); // returns 1
foo( ); // returns 2
So the above demonstrates how these properties can be used to persist data between multiple calls to a function.
I understand that properties are essentially public in the above example but is there any reason why this should not be used or why other methods of persisting data are preferred other than the obvious example of using closures to make properties private.
2 Answers 2
When there's persistent state across function calls – it's OOP. If it's OOP, then use prototypes and their instances. Instances hold the state. When you need to reset the state – simply create a new instance. No tedious micromanagement.
However, storing stuff on function objects might be good for one-time caching of some heavy calculations. Consider a function:
calcCorpuscularVelocity.COEF = Math.sqrt(Math.pow(Math.sin(Math.PI), Math.E));
function calcCorpuscularVelocity (x) {
return x * calcCorpuscularVelocity.COEF;
}
Comments
in classical OO language terms, these are are essentially public static (not just public) or class variables rather than instance variable. There is no reason not to use them if you have a use case for such a property (one that doesn't belong to a specific instance but to the function itself)