Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - Why are globals bad?

It totaly makes sense to me to use it here. What would be the alternative? How can i generaly avoid to use them and most of all why is it bad according to jsLint to make use of globals.

(function($){
  $(function(){
   $body = $('body'); //this is the BAD Global

   $.each(somearray ,function(){ $body.dosomething() });

   if (something){
     $body.somethingelse();
   }

  });
}(jQuery));

Can you help me understand this? And give me a better solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...