Naming conflicts and scoping problems increase as applications gain size, and you start to work with multiple code files and modules. In Ext JS, you can resolve these issues by creating namespaces where you can logically organize your code.
The following steps will show how to create a namespace and "hide" local variables in it. These variables will not collide with similarly-named variables that are stored in other namespaces or have global scope:
1. Define a namespace for the variables that are not global:
Ext.namespace('ExtJSCookbook.Samples');
2. Create a local variable and a global variable with the same name:
Ext JSCookbook.Samples.var1 = 'var1 (local)'; // ExtJSCookbook.Samples.var1 is limited to the ExtJSCookbook.Samples namespace var var1 = 'var1 (global)'; // var1 is a global variable
3. Prevent name collisions by putting any custom types inside the namespace you created:
// A custom type inside the Ext JSCookbook.Samples namespace ExtJSCookbook.Samples.Person = function() { return { firstName: '', lastName: '', show: function() { alert(this.firstName + ' ' + this.lastName); } } } var person1 = new Ext JSCookbook.Samples.Person(); person1.firstName = 'Jorge'; person1.lastName = 'Ramon'; person1.show();
Ext.namespace(namespace1, namespace2, namespace3,…)
and its shorthand Ext.ns(…)
allow you to create an arbitrary number of namespaces that you can use to scope variables and classes that are not global. For example, have a look at the following piece of code:
Ext.namespace('MyApplication', 'MyApplication.UI', 'MyApplication.Data', 'MyApplication.Services');
This namespace's definition above is equivalent to the following statements:
MyApplication = {}; MyApplication.UI = {}; MyApplication.Data = {}; MyApplication.Services = {};