Why are globals bad?

后端 未结 5 1686
鱼传尺愫
鱼传尺愫 2020-11-29 11:54

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 us

5条回答
  •  孤城傲影
    2020-11-29 12:46

    you should define it with var $body, then it would be local in the scope of that function, without var it could be overwritten by everybody

    (function($){
      $(function(){
       var $body = $('body'); //this is the local variable
    
       $.each(somearray ,function(){ $body.dosomething() });
    
       if (something){
         $body.somethingelse();
       }
    
      });
    }(jQuery));
    

提交回复
热议问题