Use Namespaces to organize your JavaScript code
May 28, 2008 by Aaron Conran
In today’s modern web applications it is typical to include many libraries, widgets and snippets of code from many different sources. You must be mindful that other developers may be interacting with your code simply by both sets of code being included on the same page. It is not a safe assumption that you have the entire global namespace at your disposal.
Why use namespaces?
The Ext JS forums are an example which utilizes 3 distinctly different sets of scripts from different organizations. We use Ext JS for enhancements, Google Analytics for tracking site usage and the native vBulletin scripts. You can see how all of this code from different sources has been included in the same page. You can also imagine how that there is the potential for a collision as more and more scripts are added.

When looking at Firebug’s Dom tab we can see that hundreds of variables have been created in the window when including these files. Ext consolidates all of its classes into a single namespace of Ext and further organizes its classes into various packages.

When developing your own scripts you should place all of your classes and singletons into namespaces to avoid collisions with other developers code. A namespace as defined by Wikipedia is “an abstract container providing context for the items (names, or technical terms, or words) it holds and allowing disambiguation of items having the same name”
Namespacing is important for developers in order to organize their code and ensure that their code is not overwritten when loaded in the JavaScript interpreter. If another developer defines a variable with the same name your existing definition will be overwritten. The last person to have their code included wins.
Because JavaScript is a functionally scoped language creating a function and/or variable which is not wrapped in another function will result in that variable being created in the global scope (window). To combat this, developers place their classes in Objects.
Namespaces without Ext JS
Without using Ext you could setup namespaces in the following way:
if (!App) App = {}; if (!App.form) App.form = {}; if (!App.data) App.data = {};
Ext.namespace
Ext provides the Ext.namespace method (or the shorthand Ext.ns) which will setup namespaces for you, including checking if the namespace already exists. First define the higher level namespace, then you can define various packages within your namespace. For example to setup a namespace of App and the packages form and data:
/* Ext.namespace will create these objects if they don't already exist */ Ext.namespace('App', 'App.form', 'App.data'); /* Now you can define a new class such as SampleForm inside of the App.form package */ App.form.SampleForm = Ext.extend(Ext.form.FormPanel, { initComponent: function() { /*component configuration code here! */ App.form.SampleForm.superclass.call(this); } }); /* Define MySingleton inside of the App.data package */ App.data.MySingleton = function() { return { sampleStaticMethod: Ext.emptyFn }; }();
Summary
As the client-side JavaScript included in web applications gets larger and more advanced, organization of 3rd party code and your own code becomes increasingly important. Using namespaces will ensure your JavaScript code is safe from other code overwriting it in the global namespace.


Posted on May 28th, 2008 at 1:45 pm
Thanks Aaron, great article, very well thought out and written and certainly food for thought that I will applying to my own work from now on.
Posted on May 28th, 2008 at 1:53 pm
It’s good to remember.
Thanks!
Posted on May 28th, 2008 at 1:53 pm
Very interesting. I’m new to using javascript and found this article fascinating. Thank you for sharing with a newcomer of the Ext community.
Posted on May 28th, 2008 at 7:20 pm
[...] Conran of ExtJS just published a post today recommending using namespaces to organize your Javascript code. I have a rewrite of the Ext.namespace function that I find a little more [...]
Posted on May 28th, 2008 at 10:01 pm
[...] Ext JS – Use Namespaces to organize your JavaScript code – Using namespaces will ensure your JavaScript code is safe from other code overwriting it in the global namespace. [...]
Posted on May 29th, 2008 at 5:14 am
Hello,
I completely agree with your points about the value of namespacing. In fact, I explored this topic in more depth on my blog, recently: http://higher-order.blogspot.com/2008/02/designing-clientserver-web-applications.html
That posting explores the benefits of namespacing, but goes further showing also how one can use an ‘import’ like feature to bring a long namespace into scope. For example you could write stuff like:
namespace(”com.trifork.tribook.model”);
using(com.trifork.tribook.model).run(function(m){
var rsvReader = new Ext.data.JsonReader({
root: “reservations”
}, m.Reservation);//converts JSON objects to Reservation objects
m.Room = Ext.data.Record.create([...]);//detail omitted
});
This can really help you structure large JS/Ext applications.
- Karl
Posted on May 31st, 2008 at 5:25 am
Use Namespaces to organize your JavaScript code
[...]Explains what namespaces are in JavaScript, how, when and why to use them.

Also explains how to use Ext.namespace, a convenience method in the Ext JS library to setup namespaces.[...]
Posted on June 2nd, 2008 at 8:10 pm
[...] ExtJS. Категория: JavaScriptАвтор: Spider Дата: 3 Июнь 2008 Время: 0:10 [...]
Posted on June 3rd, 2008 at 10:59 am
[...] статьи: Use Namespaces to organize your JavaScript code « Pre-Post диспетчеризация, авторизация и [...]
Posted on November 19th, 2008 at 7:18 am
Thanks, great article
Posted on January 19th, 2009 at 9:49 pm
很不错的主意,JavaScript最终会不会写起来很像C语言,甚至有一天在服务端先编译好,然后传送到客户端执行?
Posted on January 29th, 2009 at 1:11 pm
Great article. Here is an article on how to use it with the jQuery object. In other words namespasing with the jQuery http://jquery-howto.blogspot.com/2009/01/namespace-your-javascript-function-and.html
Posted on February 14th, 2009 at 12:58 am
Thanks for the read, and that was very inciteful ; very helpful post! Add me guys, please keep me updated.
Posted on May 8th, 2009 at 12:52 pm
Once again an excellent written post from you. Keep it up!
Posted on May 22nd, 2009 at 11:14 am
thanks for tutorial
Posted on June 26th, 2009 at 3:41 am
Thanks for the very useful post, it was just what I was looking for many days
Posted on July 16th, 2009 at 1:24 pm
Thanks for the topic about Namespaces! I am going to buy research papers on line or buy an essay paper with the help of the research paper writing services.
Posted on July 18th, 2009 at 9:20 am
I am grateful to you for this great content.
Posted on July 23rd, 2009 at 3:38 am
wonderful article, thankyou so much for share your knowledge!!!
Posted on August 24th, 2009 at 12:32 am
hay,
i have quetion…if i’m crete javascript in ext-js not readed??
how??
Posted on October 22nd, 2009 at 9:49 pm
What are your Terms of Service? ,
Posted on October 29th, 2009 at 5:15 pm
i am using visual studio 2005 is it possible to manage this in visual studio 2005?
Posted on November 6th, 2009 at 6:20 pm
Use Namespaces to organize your JavaScript code « Pre-Post диспетчеризация, авторизация и [...]
Posted on November 7th, 2009 at 4:34 am
Every coder must Use Namespaces to organize your JavaScript code.