Javascript 如何干净地处理全局变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5063878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cleanly deal with global variables?
提问by kheya
I have a number of aspx pages (50+). I need to declare a number(5-7) of global variables in each of these pages. Variables in one page independent of the other pages even though some might be same.
我有许多 aspx 页面(50+)。我需要在每个页面中声明一定数量(5-7)个全局变量。一页中的变量独立于其他页面,即使有些可能相同。
Currently I am declaring at the page top and outside of any function.
目前我在页面顶部和任何函数之外声明。
Should I approach this differently and is there any side effects of this approach?
我应该以不同的方式处理这个问题吗?这种方法有什么副作用吗?
If exact duplicate, please let me know. Thanks
如果完全重复,请告诉我。谢谢
采纳答案by mplungjan
It is best practice to not clutter the global scope. Especially since other frameworks or drop-in scripts can pollute or overwrite your vars.
最好不要弄乱全局范围。特别是因为其他框架或插入脚本可能会污染或覆盖您的变量。
Create a namespace for yourself
为自己创建一个命名空间
https://www.geeksforgeeks.org/javascript-namespace/
https://www.geeksforgeeks.org/javascript-namespace/
More here: https://stackoverflow.com/search?q=namespace+javascript+global
更多信息:https: //stackoverflow.com/search?q=namespace+javascript+global
Some examples using different methods of setting the vars
使用不同方法设置变量的一些示例
myOwnNS = {}; // or window.myOwnNS
myOwnNS.counter = 0;
myOwnNS["page1"] = { "specificForPage1":"This is page 1"}
myOwnNS.page2 = { "specificForPage2":"This is page 2", "pagenumber":2}
myOwnNS.whatPageAmIOn = function { return location.href.substring(location.href.lastIndexOf('page')+4)}
回答by Dan S
As @mplungjan says, best practice is to avoid global variables as much as possible.
正如@mplungjan 所说,最佳做法是尽可能避免使用全局变量。
Since window is global, you can declare a namespace at any time and within any function by using window.NAMESPACE = {};
由于 window 是全局的,您可以在任何时间和任何函数中使用 window.NAMESPACE = {}; 声明命名空间。
Then you can access NAMESPACE globally and set your values on it as properties, from within the same or another function:
然后你可以全局访问 NAMESPACE 并将你的值设置为属性,从同一个或另一个函数中:
NAMESPACE = { var1:"value", var2:"value" /* etc */ };
If you can do all this within script files rather than directly in your page then so much the better, however I guess you may not have the values available in a static script.
如果您可以在脚本文件中而不是直接在您的页面中完成所有这些操作,那就更好了,但是我猜您可能没有静态脚本中可用的值。
回答by Ravikiran
One approach would be to declare the variable on "root" level, i.e, outside any code blocks before any other JS code tries to access it.
一种方法是在“根”级别声明变量,即在任何其他 JS 代码尝试访问它之前在任何代码块之外。
You can set global variables using window.variablename = value;
in order to keep it clean superficially atleast.
您可以设置全局变量 usingwindow.variablename = value;
以使其至少在表面上保持干净。