What To Call Your Namespaces & Packages

You can practically call your namespace anything you want. Different languages seem to have their own conventions, but the reverse DNS style is what I like the most.

The idea of a namespace is to encapsulate your code, hide it behind folders unique to you. Some of the big libraries will ignore the reverse DNS rule. In JavaScript you’ll find their seems to be no rule at all.

Reverse DNS
Your DNS is unique to you, so it is a great idea to create your namespace using it.

If my domain is www.betweenthebraces.com you drop the www and flip the domain name to create your namespace.

My namespace is com.betweenthebraces.

From this point you can add your project name and any other packages you need.

For example: com.betweenthebraces.myapp.Viewport might be the location of my main class for a mobile application.

The Comma Operator

So I discovered today at a JavaScript training session with Christian Johansen that JavaScript has such a thing as a comma operator!

You may be used to a comma separator, however this is different.

Comma separator

The separator is used in declaring variables, Arrays, Objects and so forth.

var a, b, c;

var arr = [1, 2, 3];

You’ll be used to this by now, but you may not be using it to declare vars. I avoid it on Public API’s as I like to document them individually.

Comma operator

The operator is pretty unique. I have never used it yet, but now I know about it, I may find it creeping into my code.

The rules of a comma operator are that it executes from left to right and only the last value is returned. This means you can execute whatever you want after each comma and you only have to worry about the last value being returned.

var a, b;
var c = (a = 1, b = a + 2, a + b);

alert(a); // 1
alert(b); // 3
alert(c); // 4

Well the code above is pretty useless, however you may start to see the power. This same principle can be used to create a for loop with no body.

var numbers = [];

for (var i = 0; numbers.push(i), i < 10; i++);

alert(numbers); // 0,1,2,3,4,5,6,7,8,9,10

Handy little piece of JavaScript knowledge. If I were you I’d have a little play in your FireBug console.

Creating Classes in JavaScript

There is always a big argument between developers everywhere; Is JavaScript an object orientated language? Well I believe it is!

The key areas of OO are inheritance, polymorphism, abstraction and encapsulation. Now JavaScript may struggle to do all these as perfectly as some of the other languages, but it can do them.

What I’ve noticed is the server side team at work write lots of JavaScript to display their applications. What seems to missing are classes and they stream a shed load of global functions down a page of script. This style of JavaScript can lead to dirty code, that is hard to maintain, messy and tough to reuse.

If you need a reference to the terminology used in this article and what certain words mean, check out this article from Mozilla that briefly explains the terminology of OOP.
https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript#Terminology

The basics of creating a class

There is no class keyword in the JavaScript syntax, but all Function objects have the ability to become a class when you call it with the new keyword.

function Shape()
{

}

var square = new Shape();

Apart from the fact that this code is pretty useless, by calling the Shape function with new before it, the function returns a new instance of Shape. The instance of Shape now contains prototype and constructor property which is inheriting from Object.

All functions in JavaScript return a value, even if you do not define one. A function without the return statement will return itself.

It is standard practice that all functions that you intend to be used as a class start with a capital letter. The captial tells other developers that you intended the function to be used as a class.

Class constructors

The function becomes the classes constructor function. All the code that you need to execute when new Shape() goes between the braces just like if it was a regular function.

function Shape(width, height)
{
    this.width = width;
    this.height = height;
}

var square = new Shape();

In this example we have added two parameters to the class signature, which assigns the local variables to two public field variables. It is executed as follows.

var square = new Shape(100, 100);

alert(square.width); // 100

Adding functions to your class

There are many ways to add functions to your class and for each way of doing things there are pros and cons. For this blog I am going to stick to the most basic, so not to confuse people just starting out.

In JavaScript there are two types of function. Function definitions function myMethod() {} and function expressions var myMethod = function() {};. Both work equally well and to be honest I am not sure of the actual difference in performance between the two. But if you use a function definition in your class it will be encapsulated and only accessible locally to the function scope. If your function definition is on the top level it will be assigned to the global scope. But scope is a large topic and I will try my best to explain it in a forthcoming article.

Looking at the previous examples if we wish to add a public function called area, it is pretty simple.

function Shape(width, height)
{
    this.width = width;
    this.height = height;

    this.area = function()
    {
        return this.width * this.height;
    };
}

You could also add public functions to the prototype object of your class.

Shape.prototype.area = function()
{
        return this.width * this.height;
};

This is very good for inheritance, and I will be explaining defining functions in this way in an upcoming article.

So we have added a public method. The code is reusable and we are ready to add many public and private functions.

So not to add confusion I will quickly show how you do a private method.

function Shape(width, height)
{
    this.width = width;
    this.height = height;

    function calculateArea()
    {
        return this.width * this.height;
    }

    this.area = function()
    {
        return calculateArea();
    };
}

In the example above I used a function definition to create a private function. You can also create a private function using an expression var calculateArea = function() {}; but just out of personal taste I like function definitions.

The semi colon ; is very important in JavaScript. It can really can come down to whether it will work or not when minified. A tip to remember; a function definition does not need a ; after the block. Where as a function expression is treated as a variable and requires a ; at the end if the line.

There are many other ways that you can add functions, variables, properties and create classes. Here I have only described the simplest way to create a class. In an upcoming post I will be exploring classical style inheritance, scope, getters and setters which will open the doors to a whole new way to structure your script.