Globals are bad because they don't cause problems right away. Only later, after you have used them all over the place, they will cause very ugly problems - which you can't solve anymore without writing your code from scratch.
Example: You use $body
to define some functions. That works fine. But eventually, you also need a value. So you use $body.foo
. Works fine. Then you add $body.bar
. And then, weeks later, you need another value so you add $body.bar
.
You test the code and it seems to work. But in fact, you have "added" the same variable twice. This is no problem because JavaScript doesn't understand the concept of "create a new variable once." It just knows "create unless it already exists." So you use your code and eventually, one function will modify $body.bar
breaking another function. Even to find the problem will take you a lot of time.
That's why it is better to make sure that variables can only been seen on an as needed basis. This way, one function can't break another. This becomes more important as your code grows.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…