.NET-style JavaScript coding 

Organizing code into Namespaces and types, with an example of how to create the .NET Guid type.

Michael Randrup
Developers, Developers, Developers
2 min readOct 17, 2013

--

For a .NET developer, using languages like JavaScript can look like a real mess, with no obvious structure. One example is that there is no “name space-dot-through”. This normally allows you to find the code or function you are looking for very quickly, in your .NET development environment.

A way to overcome this lack of functionality in JavaScript is to organize your code, as if it is in .NET, so you can get on to making functionality instead of looking for code.

The goal of this post is to give you a brief inspiration as to how you can accomplish this, with the least amount of pain.

Organization of code into name spaces

You probably know the pain of looking at a near endless list of function() … definitions in a JavaScript file. Instead, you could organize the code into well-known namespaces.

Namespaces in JS is not supported, so you need to define a namespace as an anonymous object:

var MyNamespace = { };

You can define the contents (sub namespaces, functions, etc.) directly in the declaration, or add it later. For example, if you want to define a “Method”, you can do this:

MyNamespace.AddNumbers = function(x, y) { return x+y;};

From your code you can now reference it like this:

var result = MyNamespace.AddNumbers(1,1);

A real life example: The Guid data type

OK, now you have the basics. So let us go ahead and create a real life example.

One thing that is missing from JavaScript is the “Guid” data type. In .NET you are used to using it like this:

Guid myGuid = Guid.NewGuid();

The Guid type lives in the .NET Namespace “System.Type”, so I will try to emulate this in JavaScript. First I create the “System” namespace:

var System = {};

Next, I need to define the namespace “Type” where the Guid type lives:

System.Type = { };

Inside of the anonymous object body, I can create my Guid type (again as an anonymous object):

System.Type = { Guid: { }
};

And finally, I will put in the two most used Guid methods, so I can start using GUID’s like I am used to in .NET. The final version looks like this:

Here is the final code that makes up a JavaScript based System.Type.Guid “namespaced type”.

Now I can start coding JavaScript the way I have come to love. The .NET way:

var myGuid = System.Type.Guid.NewGuid();
var anEmptyGuid = System.Type.Guid.Empty();

--

--

Michael Randrup
Developers, Developers, Developers

Child of the computer revolution of the 80's Interests: Innovation Forward Thinking Pragmatism Alternative views Software as an art and a lifestyle