Jump to content

minimizing global variables


skaterdav85
 Share

Recommended Posts

Without a true static variable type, sometimes it cannot be helped. A global is the only variable that maintains state.If a long process requires a lot of function calls, you can pass values back and forth as arguments and return values. Since JS permits only one return value, you'll sometimes have to return an array for this to work. And yes, it can become more complicated than it's worth.Another possibility is to delete a variable when you're done with it, as in:

a = 5;alert(a); // 5delete a;alert(a); // undefined

You can organize groups of related globals into different objects, if that's any help. It doesn't relieve memory issues, but it can help with your sanity.Conventional programming practice has always said to avoid globals. A browser is a different kind of environment. Unless you do something crazy (like having a recursive process that generates a new global with every iteration), having a lot of globals is not necessarily a bad thing. A modern computer can handle almost anything you throw at it. What you really want to watch out for is generating huge numbers of GUI objects. That's where the real memory problem can get you.

Edited by Deirdre's Dad
Link to comment
Share on other sites

Interesting to hear your perspective. I was watching a video on scalable architecture by some Yahoo developer, and he made his JS very complicated. I was wondering if most developers actually do this. He stressed the importance of minimizing global variables, and so I was wondering how other developers did this (or if they do it). The simplest approach that made sense to me was to do like you said, organize variables and functions into different objects, rather than having functions and variables lie randomly outside of objects.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...