JavaScript global variables and self-naming anonymous functions

So, I read Javascript - The Good Parts , and one thing Crockford points out is the weakness of using global variables in Javascript so that if your product extends somehow and relies on a "global" variable, it may be unintentionally set.

This is all good and wonderful, and I understand the pros and cons of protecting variables in other ways, such as closing. However, I did some thoughts and wrapped the code in a function like this:

(function () { var x = 'meh'; })(); (function () { alert(typeof x); // undefined })(); 

gives it a variable scope, which thereby prevents cross-contamination of variables. I am not sure if there is a glaring flaw in this approach, although I wondered if the community has any data, or if I just overdo it and ignore the main thing.

+7
javascript
source share
3 answers

This is a completely legal way of doing things - the variables inside your function (as long as they are preceded by var ) are local to that function. It was called the module template , and it is very well received.

+6
source share

To create applications using javascript, you should try to save the variables in the local area and inside the namespace. This is a good assessment and prevention of a series of harm codes and unexpected behavior.

read this

This article talks about the benefits of this.

0
source share

Making a global function is not the answer. Why don't you do it? This keeps x out of the global namespace.

 (function () { var x = 'meh'; alert(typeof x); //string })(); 
0
source share

All Articles