1

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.

asked Oct 25, 2012 at 10:52
0

2 Answers 2

1

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;
}
answered Oct 25, 2012 at 12:48
Sign up to request clarification or add additional context in comments.

Comments

1

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)

answered Oct 25, 2012 at 10:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.