skaterdav85 Posted October 12, 2010 Share Posted October 12, 2010 I've tried researching this, but I wanted to get your thoughts on the best way to minimize global variables in your javascript. If you have a simple example, that'd be much appreciated. Link to comment Share on other sites More sharing options...
Ingolme Posted October 12, 2010 Share Posted October 12, 2010 I'd say that the solution is particular for each code and that there's no general rule. Link to comment Share on other sites More sharing options...
jeffman Posted October 12, 2010 Share Posted October 12, 2010 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. Link to comment Share on other sites More sharing options...
skaterdav85 Posted October 12, 2010 Author Share Posted October 12, 2010 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 More sharing options...
wirehopper Posted October 12, 2010 Share Posted October 12, 2010 Another option is to use namespaceshttp://www.codeproject.com/KB/scripting/jsnamespaces.aspxI usually have a few globals. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.