What does it mean global namespace would be polluted?
I don’t really understand what global namespace getting polluted means.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Quick Note On Garbage Collection
As variables lose scope, they will be eligible for garbage collection. If they are scoped globally, then they will not be eligible for collection until the global namespace loses scope.
Here is an example:
Adding this to your global namespace (at least for me) should ad 10,000 kb of memory usage (win7 firefox) which will not be collected. Other browsers may handle this differently.
Whereas having that same code in a scope which goes out of scope like this:
Will allow
arrato lose scope after the closure executes and be eligible for garbage collection.Global Namespace Is Your Friend
Despite the many claims against using the global namespace, it is your friend. And like a good friend, you should not abuse your relationship.
Be Gentle
Don’t abuse (usually referred to as “polluting”) the global namespace. And what I mean by do not abuse the global namespace is – do not create multiple global variables. Here is a bad example of using the global namespace.
This is going to create 11 global variables which could possibly be overwritten or misconstrued somewhere.
Be Resourceful
A more resourceful approach, which does not pollute the global namespace, would be to wrap this all in the module pattern and only use one global variable while exposing multiple variables.
Here is an example: (Please note this is simple and there is no error handling)