Evolution of (my) Javascript

Over the years the way that I code JavaScript has changed significantly and I wanted to review how my code has evolved. When I first started in JavaScript it might have looked something like this:

<a id='HW0' href='javascript:void(0)'
onclick='HelloWorld();'>Hello World Test 1</a>

<script type='text/javascript'>
function HelloWorld(){alert('Hello World');}
</script>

Later I learned that it was considered a good practice to mimic standard OO principles and that everything should be under one namespace so my code changed to this:

<a id='HW1' href='javascript:void(0)'
onclick='jdh1.World.Hello();'>Hello World Test 2</a>

<script type='text/javascript'>
    var jdh1 = {};
    jdh1.World = {};
    jdh1.World.Hello = function(){
    alert('Hello World!');}
</script>

Then I learned about JavaScript Object Notation (JSON) and my code looked more like this:

<a id='HW2' href='javascript:void(0)'
onclick='jdh2.World.Hello();'>Hello World Test 3</a>

<script type='text/javascript'>
var jdh2 = {
World:{
    Msg:'',

    Hello: function(){
        alert(jdh2.World.Msg);
    },

    Initialize: function(Settings){
        jdh2.World.Msg= Settings.Message;
    }
}
};

jdh2.World.Initialize({Message:'Hello World?'});

</script>

A while later I learned that my HTML really shouldn't have javascript embeded in it (e.g. no onclick) and also found out about self-executing anonymous functions (which I see no real need for, but find strangely irresistable), so my code morphed ever so slightly to this:

<a id='HW3' href='javascript:void(0)'>
Hello World Test 4</a>

<script type='text/javascript'>
var jdh3 = {
World:{
    Msg:'',

    Hello: function(){
        alert(jdh3.World.Msg);
    },

    Initialize: function(Settings){
        jdh3.World.Msg= Settings.Message;
    }
}
};

(function(){/*Page Initialization*/
    document.getElementById('HW3').onclick = 
    jdh3.World.Hello;
    jdh3.World.Initialize(
        {Message:'Hello World???'}
    );
})();

</script>

Finally I started using frameworks, such as JQuery and Asp.Net ajax which are more assistive than transformative and don't really apply to this example (though they allow you to replace that pesky getElementById with either dollar-sign($) or $get).

I have, however, mostly avoided the Moo Tools framework — which attempts to transform javascript from a prototyped object oriented language into class inheritance based one — for the same reason that I avoid prototypes themselves; within the context of my programming they add complexity without much gain (again strictly speaking within the context of my development).

I must say that I am ethusiastically embracing the the combination of ajax(via ASP.net) and DHTML(via jQuery); they complement one another beautifully.

0 comments: