# IT:AD:JScript:Namespaces # * [[../|(UP)]] {{indexmenu>.#2|nsort tsort}} //Verifying if the variable "com" exists in order to use it, //if it doesn't exists we create an empty object var com = com || {}; //and add it to the object "quizzpot" com.quizzpot = com.quizzpot || {}; com.quizzpot.tutorial = com.quizzpot.tutorial || {}; //Creating the constructor of the object com.quizzpot.tutorial.User = function(options){ this.nickname = options.nickname; } //Creating an instance var p = new com.quizzpot.tutorial.Person({name:'John'}); var u = new com.quizzpot.tutorial.User({nickname:'stock'}); //displaying it in the console console.debug(u); console.debug(p); Note that `ExtJS` solves it with a method as follows: Ext.namespace('com.quizzpot.tutorial'); Ext.namespace('App', 'App.form', 'App.data'); //or you can use the shortcut Ext.ns('com.quizzpot.tutorial'); Of which the source code is: namespace : function() { var ln = arguments.length, i, value, split, x, xln, parts, object; for (i = 0; i < ln; i++) { value = arguments[i]; parts = value.split("."); object = (window.Ext) ? window[parts[0]] = Object(window[parts[0]]) : arguments.callee.caller.arguments[0]; for (x = 1, xln = parts.length; x < xln; x++) { object = object[parts[x]] = Object(object[parts[x]]); } } return object; } 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.initComponent.call(this); } }); /* Define MySingleton inside of the App.data package */ App.data.MySingleton = function() { return { sampleStaticMethod: Ext.emptyFn }; }(); If not using ExtJS or SenchaTouch, consider: * [http://blog.arc90.com/2008/06/06/an-easy-way-to-implement-namespaces-in-javascript/](http://blog.arc90.com/2008/06/06/an-easy-way-to-implement-namespaces-in-javascript/) * or maybe the following as the above game me a little grief to get going. * [http://weblogs.asp.net/mschwarz/archive/2005/08/26/423699.aspx](http://weblogs.asp.net/mschwarz/archive/2005/08/26/423699.aspx) ## Registering versus Namespaces * [http://www.sencha.com/forum/showthread.php?125034-Sencha-MVC-components-Registering-vs.-Namespaces](http://www.sencha.com/forum/showthread.php?125034-Sencha-MVC-components-Registering-vs.-Namespaces) ## Resources ## * [http://www.quizzpot.com/2009/04/packages-and-namespace/](http://www.quizzpot.com/2009/04/packages-and-namespace/) * [http://www.sencha.com/blog/use-namespaces-to-organize-your-javascript-code/](http://www.sencha.com/blog/use-namespaces-to-organize-your-javascript-code/)