为什么全局变量不好? [英] Why are globals bad?

查看:196
本文介绍了为什么全局变量不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里使用它对我来说是完全有意义的。
会有什么替代方案?我怎么能完全避免使用它们,最重要的是根据jsLint使用全局变量的原因很糟糕。

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?

推荐答案

Globals很糟糕,因为它们不会立即引起问题。只有到了以后,在你到处使用它们之后,它们才会引起非常难看的问题 - 如果不从头编写代码,你就无法解决这些问题。

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.

示例:您使用 $ body 来定义一些函数。这很好。但最终,你还需要一个价值。所以你使用 $ body.foo 。工作良好。然后添加 $ body.bar 。然后,几周后,你需要另一个值,所以你添加 $ body.bar

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.

你测试代码它似乎工作。但事实上,你已经添加了两次相同的变量。这不是问题,因为JavaScript不理解一次创建一个新变量的概念。它只知道创建,除非它已经存在。所以你使用你的代码,最终,一个函数将修改 $ 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.

这篇关于为什么全局变量不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆