问题描述
我有许多aspx页面(50+)。
我需要在每个页面中声明一个数字(5-7)的全局变量。
一个页面中的变量独立于其他页面,即使有些页面可能相同。
目前我在页面顶部和任何函数之外声明
我是否应该以不同的方式处理这种方法?是否有这种方法的副作用?如果确实重复,请让我知道。
谢谢
最好不要混淆全局范围。尤其是因为其他框架或嵌入脚本可能会污染或覆盖您的变量。
为您自己创建一个名称空间
更多信息:
使用不同方法设置变量的一些示例
ProjapatiNS = {}
ProjapatiNS.counter = 0;
ProjapatiNS [page1] = {specificForPage1:This is page 1}
ProjapatiNS.page2 = {specificForPage2:This is page 2,pagenumber:2}
ProjapatiNS.whatPageAmIOn = function {return location.href.substring(location.href.lastIndexOf('page')+ 4)}
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.
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
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
http://www.javascripttoolbox.com/bestpractices/#namespace
More here: https://stackoverflow.com/search?q=namespace+javascript+global
Some examples using different methods of setting the vars
ProjapatiNS = {}
ProjapatiNS.counter = 0;
ProjapatiNS["page1"] = { "specificForPage1":"This is page 1"}
ProjapatiNS.page2 = { "specificForPage2":"This is page 2", "pagenumber":2}
ProjapatiNS.whatPageAmIOn = function { return location.href.substring(location.href.lastIndexOf('page')+4)}
这篇关于如何干净地处理全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!