Why are globals bad?

后端 未结 5 1692
鱼传尺愫
鱼传尺愫 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:58

    You could rewrite that as

    var $body = $('body');
    

    That (the use of the var keyword) would make it a local variable, which is enough for your purposes. It will still be within scope in your each callback.

    The reason it's bad to use globals is that it can be overwritten by anything else. For your code to scale well, it becomes dependent on what other scripts you use. It's preferable to keep the script as self-sufficient as possible, with as little as possible dependencies pointing to the world outside of it.

提交回复
热议问题