Javascript is a rather curious language. It began it’s life as a language used mainly for form validation and a few special effects, and has matured into a language that can now do just about anything other languages can do. Using Google’s O3D, Javascript can do 3D graphics, using Titanium it can be used to write desktop applications, andin it’s regular position t functions well in a web application environment.

With all these modern demands being made on Javascript, there is one feature that is severely lacking – classes.

We are fortunate, however, as due to the way in which functions are handled in Javascript, functions are able to be substituted in place of class definitions.

As an example

ExampleClass = function() {
   var text = 'Hello ';

   this.testFunction = function(name) {
      alert(text + name);
   }
}

instance = new ExampleClass();
instance.testFunction('Serge');


It seems like quite a strange idea at first, but makes Javascript able to compete with real object orientated languages, and also allows the code to be neater and able to be written in a more modular way. Traditional Javascript is notorious for having tons of variables and functions floating around in the global scope.

It must be said, however, that this is a rather limited way of doing object orientated programming since it does not easily allow inheritance, and while the scope of variables can be either private or public (denoted by the use of the this keyword), concepts such as protected and virtual functions are not supported.

Overall though, I just think it is awesome that this can be done at all with a langauge that’s main use was making sure your email address was entered correctly.

Share