Javascript namespace

来源:互联网 发布:java elseif怎么用 编辑:程序博客网 时间:2024/06/09 15:34
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 24Various getting started with JavaScript resources (relevant to Ext)
原创粉丝点击