Javascript namespace

ThinkSharp.org » Ext General
One of the big problems as the number of toolkits that you can use in your RIA increases is variable collision. Constructing your classes and widgets in the form of a namespace reduces the risk that the global variables you are using will have been used by someone else. The following code demonstrates a pattern for defining a namespace utilizing objects to create an object hierarchy for your namespace. 1: var MyNamespace = {}; 2: MyNamespace.test = function(){ 3: alert(“MyNamespace.test”); 4: }; 5: 6: MyNamespace.common = {}; 7: MyNamespace.common.test = function(){ 8: alert(“MyNamespace.common.test”); 9: }; 10: 11: MyNamespace.utilities = {}; 12: MyNamespace.utilities.test = function(){ 13: alert(“MyNamespace.utilities.test”); 14: }; 15: 16: MyNamespace.common.dataaccess = {}; 17: MyNamespace.common.dataaccess.test = function(){ 18: alert(“MyNamespace.common.dataaccess.test”); 19: }; 20: 21: Notice that before the namespace can be assigned variables and functions, it needs to be initialized to an empty object. This allows you to make calls like: MyNamespace.common.dataaccess.test(); However, it is important that you only initialize the name space object once, and it is important that the full path of namespace objects be declared before you try and assign functions and properties to them. If you want to separate your name space implementation across separate files, then you really need to check that all the stages of the namespace are assigned and create them if not. e.g. 1: if(!MyNamespace) MyNameSpace = {}; 2: if(!MyNamespace.common ) MyNameSpace.common = {}; 3: if(!MyNamespace.common.dataaccess) MyNameSpace.common.dataaccess = {}; You can imagine that if your namespaces get quite deep, you start having quite a lot of code at the start of each of your Javascript files just to ensure the namespace objects are created. There is however a very nice solution in the Ext library which helps you with this: Ext.namespace() - this takes a variable list of namespace names and creates the objects for you if they don’t exist. e.g. 1: Ext.namespace(“MyNamespaces”,“MyNamespace.common”,“MyNamespace.common.dataaccess”); Apr 24 Various getting started with JavaScript resources (relevant to Ext)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值