简体   繁体   English

全局变量javascript,java,php,所有语言

[英]global variables javascript, java, php, all languages

I always read on the web that global variables are bad, and I understand that they are bad because each function has access to them and if each function in the application modifies the global variable, in a large application, it can become very difficult to trace the state of this variable at a particular point in the code. 我总是在网上读到全局变量不好,而且我理解它们很糟糕,因为每个函数都可以访问它们,并且如果应用程序中的每个函数都修改了全局变量,那么在大型应用程序中,跟踪起来会变得非常困难。该变量在代码中特定点的状态。

But my question is this, if I have a variable that each function is going to need to use anyway, isn't it better to declare it as global? 但是我的问题是,如果我有一个无论如何都要使用每个函数的变量,将其声明为全局变量是否更好? instead of having to instantiate my variable every time inside each function? 不必每次在每个函数中都实例化我的变量?

Also, when should I use global variables as opposed to local variables? 另外,什么时候应该使用全局变量而不是局部变量?

Every variable represents some real or imaginable entity. 每个变量代表某个真实或可想象的实体。 If you are sure that entity is unique, then it's OK to have static variable for it. 如果您确定实体是唯一的,则可以为其具有静态变量。 For example, screen/keybord/mouse devices are represented with static variable of type java.awt.Toolkit (accessible via getter). 例如,屏幕/键盘/鼠标设备用java.awt.Toolkit类型的静态变量表示(可通​​过getter访问)。 But such cases a rare. 但是这种情况很少见。 Usually, programmer thinks of single instance of entity, and declares a static variable for it, and then a need for another similar entity arise, which ends in laborious refactoring. 通常,程序员会想到实体的单个实例,并为其声明一个静态变量,然后需要另一个类似的实体,从而导致费力的重构。

This is all about memory utilization while code is running. 这全部与代码运行时的内存利用率有关。 You always try to keep less number of object into the memory while code running.Object with less scope(method scope) your object will live less in memory hence good memory utilization. 您总是尝试在代码运行时将较少数量的对象保存到内存中。如果对象的作用域(方法范围)较小,则对象在内存中的生存时间会减少,因此内存利用率较高。 So need to keep variable as less scope as it is necessary. 因此需要将变量保持在必要的范围内。 But your statement for global variable is not fully correct as in java we have access modifier (public,private,default etc) and if any global variable(class variable) has private modifier then it cannot be modified by outside the class. 但是您对全局变量的声明并不完全正确,因为在Java中我们具有访问修饰符(public,private,default等),如果任何全局变量(类变量)具有private修饰符,则无法在类外部进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM