Archive for the ‘object-oriented’ Category.

How to write a singleton class in javascript

[UPDATE : This post is outdated. Check out the new post on singletons.]

If I look at my stats, a lot of people are wondering how to write a singleton class. I already wrote about it before but my old solution exposed the instance of the class so more than one instance could be created thus making it not completly a singleton class.

Here’s the new solution using a private variable for the instance.

How to create an object with private variables and methods

In short, you can use private variables when you return another scope when declaring a class.

  1. function Cats() {
  2.   var nameList = []; // private var
  3.        
  4.   // This is where you define another scope!
  5.   return {
  6.     add:function(name) {
  7.       nameList.push(name);
  8.     }
  9.   }     
  10. }

How does it work?

The magic lies in creating a different scope at the end of the class definition that does not include private variables. Then, private members are available in this scope and not outside of it, thanks to the power of closures.

Differences between private and public

These two classes definition shows the difference between the a class where all members are public versus a class where some members are private.

This is a class where all members are public.

  1. function PublicCats() {
  2.   // This is the list of cat names
  3.   this.nameList = [];
  4.  
  5.   // This is a method that I would like to be private but can’t
  6.   // It returns the last cat of the list
  7.   this.lastCat = function() {
  8.     return this.nameList[this.nameList.length-1];
  9.   }
  10.  
  11.   // Return the list of names
  12.   this.names = function() {
  13.     return this.nameList;
  14.   }
  15.  
  16.   // Add a name to the list
  17.   this.add = function(name) {
  18.     this.nameList.push(name);
  19.    
  20.     // Return the last cat just added
  21.     return this.lastCat();
  22.   }  
  23. }

This is the corresponding class where some members are private.

  1. function PrivateCats() {
  2.   // This is the list of cat names
  3.   var nameList = [];
  4.  
  5.   // This is a private method
  6.   var lastCat = function() {
  7.     // Note : I don’t use "this" to access private variables
  8.     // thanks to the power of closures!
  9.     return nameList[nameList.length-1];
  10.   }
  11.  
  12.   // These are our public methods!
  13.   // This is where we create another scope to
  14.   // avoid external objects to use the private variables.
  15.   return {
  16.     add:function(name) {
  17.       // Note : once again, I don’t use "this"
  18.       // to access the private variables and methods
  19.       nameList.push(name);
  20.       return lastCat();
  21.     },
  22.     names:function() {
  23.       return nameList;
  24.     }
  25.   }  
  26. }

In the above code, line 15 makes all the difference between the two classes.

On GitHub

Get all the code on GitHub and see it live in action on my GitHub page.

Ask Dan : Procedural VS object-oriented in javascript

Since the beginning of Ask Dan a javascript question, I received a bunch of questions. Here’s the first one I received. It’s from Andrew Worcester.

There seems (to me anyway) to be an overuse of the “new” syntax in libraries. If I create an Ajax object is there a functional benefit to using: “new Ajax.Request(options)” verses something like “sendAjaxRequest(options)” It seems to me that by using “new” causes more hassle because you need to be sure the objects are properly disposed of. So is there a performance or functional benefit to this technique?

I had a hard time understanding the question (and I was too ass hole to ask…) so I’ll rephrase it in another way : is there a benefit from using object-oriented techniques VS procedural in javascript?

Procedural in javascript

Though javascript was not a procedural language from the start, it has been overused as such in the beginning (and it’s still is). That may be because people didn’t bother learning javascript and they copy/pasted functions from sites that offers low-quality javascript snippet. All they did was “hacking” the poorly written code to suit their needs. This technique worked for a long time but with the use of ajax and DHTML, it’s nearly impossible to have clean code that is not buggy and dirty.

Object-oriented in javascript

The new statement necessary implies the use of objects in javascript. You can have basic information about object in How to create objects in object-oriented javascript and in with the articles tagged Object-oriented of this site.

The benefit of object-oriented

There is one major benefit about object-oriented that creates a lot of other benefits : the cleanliness of the code. The other benefits from that are : the code is easier to maintain, to modify, to read and to explain.

OO applied

I’ll apply it to an example. I want to alert the sound of cat by ajax.

In a procedural way, you’ll approximatively have

  1. // Global variable
  2. ajaxRequest = null;
  3.  
  4. function sendCatSoundAjaxRequest() {
  5. ajaxRequest = new XMLHttpRequest(); // Create the request in the global var
  6. // … code for request …
  7. }
  8.  
  9. function receiveCatSoundAjaxRequest() {
  10. // The sound is in clear text in the response
  11. alert(ajaxRequest.responseText);
  12. }

The problems? You have a global variable to keep track of the ajax request. Because it could be use by every other functions that need ajax, you can’t make more than one request at a time. Also, there are nothing that binds the two methods together apart their names that are look alike. Now, just think of the code when you have 5 or 6 different type of requests. Your code will look like garbage.

In a object-oriented way, you would all write this ugly code in a separated object. Your main call to see the sound of a cat could be something like

  1. var cat = new Cat();
  2. alert(cat.getSound());

The code from above still exists somewhere but the complexity is now hidden behind the Cat class.

How to inherit classes in javascript

First of all, since I made the front page of Ajaxian, a lot of new readers joined in. Welcome to all of you. I would also take a moment to explain that Javascript Kata is a technical blog about javascript and though I will talk here and there about ajax, it is not focused on that subject. It is more about the good javascript techniques that should come along with all the ajax you have to do. I update this site 2 or 3 times a week. Keep reading!

There are hundreds of ways to do inheritance in javascript but a single one is simpler, cleanier and prettier than all the other ones.

Note!
Before reading this article, you should take a look at
How to create objects in object-oriented javascript.

A one-liner

To inherit a class in javascript, it’s a one-liner

  1. TheSubClass.prototype = new TheParentClass();

As simple as that!

Where to write the one-liner

The problem with that one-liner is where should it goes? Once again, the answer is simple : after the constructor of the sub-class. It may look strange but it is extremely effective.

  1. /* The constructor of the Mammal class */
  2. function Mammal() {
  3. }
  4.  
  5. /* The constructor of the Cat class */
  6. function Cat() {
  7. }
  8. // The magic that inherits Cat from Mammal is here!!!!!
  9. Cat.prototype = new Mammal();

Is this true inheritance?

In the hundreds of other ways of inheriting classes in javascript, I think that this is the only one that is a true inheritance. What do I mean by true inheritance? I mean that javascript recognizes it as a sub-class of the class. Check this out!

  1. /* Above code goes here */
  2.  
  3. // Create a cat
  4. var theCat = new Cat();
  5.  
  6. // Check if the cat is an instance of the Cat class
  7. if (theCat instanceof Cat) {
  8.     alert("theCat is an instance of the Cat class");
  9. }
  10.  
  11. // Check if the cat is an instance of the Mammal class
  12. if (theCat instanceof Mammal) {
  13.     alert("theCat is an instance of the Mammal class");
  14. }

If you execute this code, you’ll see that the cat is an instance of the Cat class and the Mammal class.

How to use the self with object-oriented javascript and closures

When I began with object-oriented javascript, I always saw a self here and there without fully understanding what it meant.

Self?

When you see self in some object-oriented javascript, it’s just mean that the developer is using a closure that will reference the current object via a variable named self. Because self is a variable, it could be named anything else. The use of “self” as a name is a unwritten convention but it could be whatever you want.

  1. // Create a cat
  2. function Cat() {
  3.     this.theCatName = "Mistigri";
  4. }
  5.  
  6. // The cat will meow later
  7. Cat.prototype.meowLater = function() {
  8.     // I create the variable self that refers to the this (the current object)
  9.     var self = this;
  10.  
  11.     // I create a timeout that calls the self.meow function within an anonymous function
  12.     /*** NOTE : You don’t always have to create an anonymous function it’s just that in
  13.         this case, it is required ***/
  14.     window.setTimeout(
  15.         function() {
  16.             self.meow();
  17.         }
  18.         , 1000);
  19. }
  1. // The cat meows
  2. Cat.prototype.meow = function() {
  3.     // I can use the this expression!!!
  4.     alert(this.theCatName + " : meow!");
  5. }
  6.  
  7. // I crate an object and call the meowLater() function
  8. var theCat = new Cat();
  9. theCat.meowLater();

Why not use the this?

Because when using closures within an object, the this in the called function (in the above example, in the meow() function) is the window object.

How to make a singleton in javascript

[UPDATE : This post is outdated. Check out the new post on singletons.]

Singleton is one of the most common and easiest design pattern. In fact, a lot of designs are wrong just because the developer didn’t know about singletons and design patterns (I could have said : a lot of my designs were wrong just because I didn’t know about singletons and design patterns).

I was looking at the first three results for singleton javascript on Google and I was more than deceived by what they had to tell us. That’s why I write this article.

What is a singleton class?

A singleton is when your application needs to use just one instance of an object to centralize your access to it. Example, I have a list of cat names that can be used in various functions of an application. Sometimes, names are added or removed. I could use a global variable to the page containing the list. The problems are :

- It’s a global variable (global variables are bad).
- I don’t know when the list is created or initialized.
- If you reuse your class in another project, you will always need to define a global variable and instance it correctly.
- It’s ugly.

If I use a singleton pattern, the advantages are :

- The object is always correctly created.
- You don’t have to ask yourself questions about the state of the list or whatever. It just works!
- Another programmer can recognize the singleton pattern thus making it easier for him to work.

How to write a singleton class

Before writing a singleton, you need to know about creating objects and static functions.

  1. // I create the class
  2. function CatNames() {
  3.         this.names = new Array(); // The array that will contain the names
  4. }
  5.  
  6. CatNames.instance = null; // Will contain the one and only instance of the class
  7.  
  8. // This function ensures that I always use the same instance of the object
  9. CatNames.getInstance = function() {
  10.         if (CatNames.instance == null) {
  11.                 CatNames.instance = new CatNames();
  12.         }
  13.  
  14.         return CatNames.instance;
  15. }
  16.  
  17. // Function to add a cat name
  18. CatNames.prototype.add = function(catName) {
  19.         this.names.push(catName);
  20. }
  21.  
  22. // Function to remove the last cat name
  23. CatNames.prototype.removeLast = function() {
  24.         return this.names.pop();
  25. }
  26.  
  27. // Function to alert all cat names
  28. CatNames.prototype.alertAllCats = function() {
  29.         alert(this.names.join(","));
  30. }

I use it in these functions.

  1. function addThreeNames() {
  2.         // I use the one and only instance of the class (the magic of singletons)
  3.         var names = CatNames.getInstance();
  4.  
  5.         names.add("Mistigri");
  6.         names.add("Bibi");
  7.         names.add("Gary");
  8. }
  9.  
  10. function removeLastCat() {
  11.         // Once again, singleton is here
  12.         var names = CatNames.getInstance();
  13.  
  14.         names.removeLast();
  15. }
  16.  
  17. // I call the functions
  18. // – no need for a global variable
  19. // – no need to create the object and pass it as parameter
  20. addThreeNames();
  21. removeLastCat();
  22.  
  23. // Alert all cats
  24. var names = CatNames.getInstance();
  25. names.alertAllCats();

The downside of this technique

Yes I know, you can instantiate the singleton class if you want.

  1. var catNames = new CatNames();

You know what? You’ll have to follow a simple rule : never instantiate a singleton class. Maybe we could use more techniques that would protect you from instantiating your own singleton class but it would be a waste of time and code.

Looping through object properties and hash tables using the “in” statement

As I said earlier, objects are hash tables of properties and functions so looping throught them is done the same way (weepee!).

The “in” statement

The in statement must be used in a for loop. Like this : for (var element in allElements). In most of the other languages, the element variable would contain the complete element but in javascript, it contains the name that refers to the complete element.

Looping through a hash table

Before doing it, maybe you should take a look at How to use javascript hashes (or hash-table) to make sure you fully understand what are javascript hash tables.

[source:javascript]

// I create a hash table
var hashPetNames = new Object();

// I create the pets
hashPetNames["cat"] = “Mistigri”;
hashPetNames["dog"] = “Rex”;
hashPetNames["bird"] = “Bibi”;

// I loop using the “in” statement
for (var name in hashPetNames) {
alert(“My ” + name + “‘s name is ” + hashPetNames[name]);
}

[/source]

Run this code and you should see the alerts :
- My cat‘s name is Mistigri.
- My dog‘s name is Rex.
- My bird‘s name is Bibi.

So easy.

Looping through an object

This one is a little kinkier. Why would I want to loop through an object properties and methods? I can’t give you an answer. It’s up to you to find it. I’ve used it a couple of times so it’s not as useless as you could think.

Example, I would like to separatly alert all the properties and methods of an object.

[source:javascript]

// Create the class
function TheClass() {
this.name = “The class”;
this.fullName = “The full name of the class”;
this.age = “51″;
}

// Add a function
TheClass.prototype.alertClass = function() {
alert(this.name + ” ” + this.fullName + this.Age);
}

// Construct the object
var theObject = new TheClass();

// Loop through the properties/functions
var properties = “”;
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties += propertyName + “, “;
}
}

alert(“Properties : ” + properties);

// Loop through the properties/functions
var functions = “”;
for (var functionName in theObject) {
// Check if it’s a function
if (theObject[functionName] instanceof Function) {
functions += functionName + “, “;
}
}

alert(“Functions : ” + functions);

[/source]

How to write constants in javascript

YOU CAN’T. As simple as that. Anyway, what is a constant? A constant is a unchangeable variable that throws an error when you try to write in it. Thus, implementing constant in javascript would be against its will to be opened. The magic of javascript resides in the liberty it gives you to change anything you want, anywhere you want. Even if you’re not the owner of the object. Even if it’s a javascript intrinsic class. Why would you want to have constants???

Still, everyone wants to use constants (myself included). Here are a couple of ways of doing it without actually doing “it”.

Global constants

Ouch! That one hurts! As I said earlier, global variables are prohibited since 1992 by GVIP (Global Variables International Police). But sometimes, a man gotta do what a man gotta do. If you really can’t find any better solution, use this one.

[source:javascript]
var DISPLAY_TYPE_SMALL = 0;
var DISPLAY_TYPE_BIG = 1;
[/source]

Class constant

If you already know how to create objects you have to use the class functions technique (also knows as static or shared functions) to create a class “constant”.

[source:javascript]
// Create the class
function TheClass() {
}

// Create the class constant
TheClass.THE_CONSTANT = 42;

// Create a function for TheClass to alert the constant
TheClass.prototype.alertConstant = function() {
// You can’t access it using this.THE_CONSTANT;
alert(TheClass.THE_CONSTANT);
}

// Alert the class constant from outside
alert(TheClass.THE_CONSTANT);

// Alert the class constant from inside
var theObject = new TheClass();
theObject.alertConstant();
[/source]

As you saw, you can’t access the constant using the this variable (a reference to the current object) because the constant is defined on the class only and not the object.

Class enum

Sometimes, constants are not enough. You need to regroup them to be more logical. Example? I have three different display type : small, medium, big. I could do this

[source:javascript]
// Create the class
function TheClass() {
// Initialize the display type to big
this.displayType = TheClass.DISPLAY_TYPE_BIG;
}

// Create constants
TheClass.DISPLAY_TYPE_SMALL = 0;
TheClass.DISPLAY_TYPE_MEDIUM = 1;
TheClass.DISPLAY_TYPE_BIG = 2;

// Assign the small display type to the object
var theObject = new TheClass();
theObject.displayType = TheClass.DISPLAY_TYPE_SMALL;
[/source]

It works but they are not logically grouped. I would prefer to use an enumeration (enum) [more info about enum].

[source:javascript]
// Create the class
function TheClass() {
// Initialize the display type to big
this.displayType = TheClass.DISPLAY_TYPE.big;
}

TheClass.DISPLAY_TYPE = {
small : 0,
medium : 1,
big : 2
}

// Assign the small display type to the object
var theObject = new TheClass();
theObject.displayType = TheClass.DISPLAY_TYPE.small;
[/source]

This is what I call beautiful code.

One simple rule

Knowing that there’s no mechanism that prevents you from modifying your “constants”, follow that simple law : don’t modify your constants.

How to do class functions in javascript (aka static or shared functions)

One of the really concept of the object-oriented programming is the class functions but they are also known as static functions (Java, php, C++) or shared functions (.NET).

Why using class method?

Class methods help you keeping your code clean by centralizing your functions. Example, you create a calendar object that formats a string from two dates to have readable time difference (example, input : “2007-08-13″ and “2007-08-16″, output : “begins august 13th 2007 and ends 3 days later”).

Sure you can create a readableTime(beginDate, endDate) function. First problem is that there may be another function with that name. Second problem? If another programmer works on the code that makes a call to readableTime function, how does he knows that it comes from the javascript file containing the Calendar object?

So, you could create a Calendar_readableTime(beginDate, endDate) function. Great! But what if the object name Calendar changes for BestCalendar? The Calendar_readableTime function won’t have the good suffix.

The solution is to use a class function so the call to the readableTime function will look like this : Calendar.readableTime(beginDate, endDate). Nice looking and clean code.

How to create a class function

First, you create a class

[source:javascript]
function Calendar() {
}
[/source]

Second, you add the class function

[source:javascript]
function Calendar() {
}

Calendar.readableTime = function() {
// Code here
}
[/source]

Then, it’s ready to be called in your code

[source:javascript]
var cal = new Calendar();
var beginDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + 3); // Add three days to endDate

var stringTime = Calendar.readableTime(beginDate, endDate);
[/source]

Difference with other languages

In many other languages, your class functions are callable from an instantiated object like this.

[source:javascript]
var cal = new Calendar();
var beginDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + 3); // Add three days to endDate

// I call cal.readableTime and it doesn’t work!
var stringTime = cal.readableTime(beginDate, endDate);
[/source]

In javascript, it doesn’t work because the function readableTime is assigned to the class only and is not referenced in the instances of the class.

To give the access to the readableTime function on the instance of an object is to create the function this way :

[source:javascript]
function Calendar() {
}

Calendar.readableTime = new function() {
// Code here
}

// Here’s the magic
Calendar.prototype.readableTime = Calendar.readableTime;
[/source]

By assigning the function to the prototype, each object of the Calendar type will have the readableTime function.

How to create objects in object-oriented javascript

[UPDATE : This post is outdated. Check out the new post on how to create objects.]

Javascript is a functional programming language thus having no “real” objects. You can write it the way you want : procedural spag, functional, object or whatever word you know. Why should I write it object-oriented? Because, OO has proven many times its ease of use and great encapsulation. In this paper, I won’t talk about why but about how.

There are hundreds of way of writing OO javascript, I tried a lot of the most commons and I finally adopted one : oo using prototypes.

1. Creating an empty class

I like cats so here’s a complete example for a cat that meows.

First, I create an empty class.

[source:javascript]
function Cat() {
}
[/source]

Hmmmm… that looks a lot like a function. In fact, it’s a function. Why classes are function? Because javascript is a functional language. More on that later (maybe).

2. Creating the constructor

When I have a cat that meows, I want to see its name. I add a name property that is initialized in the constructor of the class.

[source:javascript]
function Cat(name) {
this.name = name;
}
[/source]

What is this? This, is a reference on the current instance of the object. By calling this.name = name, we instantiate an public variable for the object that has the value name (the name of the cat).

3. Adding a instance method

As I said earlier, I want the cat to meow. So, I will add a meow() method to the class that will be available to every instance.

[source:javascript]
function Cat(name) {
this.name = name;
}

Cat.prototype.meow = function() {
alert(“meow!”);
}
[/source]

I used the class’ prototype. This is one of the hundred ways of adding a method but it’s the best way because we create a single reference for all the objects of that class.

4. Using variables of an object

Hey, didn’t you read the specs? I said that I wanted to see the name of the meowing cat.

[source:javascript]
Cat.prototype.meow = function() {
alert(this.name + ” : meow!”);
}
[/source]

Did you see? I used the this (reference on the current instance of the object). By doing that, I simply call the variable that I defined in my constructor (see point #2).

5. Making the cat meow

Now I’m ready to make the cat meow. On the onload property of the body element, I call a function named bodyOnload.

<html>
<body onload=’bodyOnLoad();’ />
</html>

In the bodyOnLoad function, I create a Cat object and call the meow() method.

[source:javascript]
function bodyOnLoad() {
var mistigri = new Cat(‘Mistigri’);
mistigri.meow();
}
[/source]

I should see an message box with the message “Mistigri : meow!” inside.

In conclusion

Ok, that was an easy one but though it may seem obvious to you, it is not alway as clear for some of my fellows. The important thing I wanted to show was how to create a class method (see point #3). This is the best/safest/fastest way of doing this.