如何干净地处理全局变量? [英] How to cleanly deal with global variables?

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

问题描述

我有许多aspx页面(50+)。
我需要在每个页面中声明一个数字(5-7)的全局变量。
一个页面中的变量独立于其他页面,即使有些页面可能相同。



目前我在页面顶部和任何函数之外声明



我是否应该以不同的方式处理这种方法?是否有这种方法的副作用?如果确实重复,请让我知道。
谢谢

解决方案

最好不要混淆全局范围。尤其是因为其他框架或嵌入脚本可能会污染或覆盖您的变量。



为您自己创建一个名称空间



http://www.javascripttoolbox.com/bestpractices/#namespace



更多信息: https://stackoverflow.com/search?q= namespace + javascript + global



使用不同方法设置变量的一些示例

  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)}

这篇关于如何干净地处理全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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