Heckroth Industries

Object Oriented

JavaScript classes

There are so many ways to create a class in JavaScript that I have spent a few days reading up on them to figure out the best way to implement a class. What I wanted was the ability to create a class as one that can easily be reused, not as a single instance of a class like lots of tutorials show.

I also wanted to make it easier to have each class defined in a separate file, at least in the development stage. These files could be concatenated for the production instance of a website if performance is required.

The method that I favour at the minute, as it meets the above requirements, is

function EXAMPLE_CLASS() {
    this.variable = 10;

    function popup() {
        alert(this.variable);
    };

    EXAMPLE_CLASS.prototype.popup = popup;

To create an instance of this class use

var classInstance=new EXAMPLE_CLASS();

Defining classes like this makes it nice and easy to create multiple instances of the same class as well as helping keeping your code nice and clean.

The popup function is defined within the class to keep it out of the global namespace, after all a lot classes will want to share methods with the same name and while it is possible to point a class’s method to any function name it makes it a bit simpler to find the function that relates to a method if it has the same name.

The prototype line in the class definition function means that rather than each class instance having a seperate popup function one function will be created by the JavaScript interpreter and used for every instance of the class. This is generally a good thing to do unless you have a very good reason why each instance of a class should have it’s own functions rather than sharing them.

Jason — 2010-06-29