Ahmed Nuaman


builder of internets ~ developer of dreams ~ tamer of Dachshunds

How to create a JavaScript class constructor

Now if you’ve been reading my blog posts I’m sure you’ll be familiar with my rants regarding JavaScript’s lack of class-based coding. I explained in this blog post how you can write ‘classes’ in JavaScript but I omitted how to make use of the constructor.

A constructor is useful because you’re able to do this:

new MyClass( 'foo' );

And this’ll start things going. Normally in a class based language we make use of constructors by sticking them at the top of the class, however in JavaScript we need to tell the class to fire that function as it’s called, like so:

var MyClass = function(v)
{
    function constructor()
    {
        document.write(v);
    }
       
    constructor();
};

new MyClass( 'foo' );

This will print ‘foo’ (or whatever the hell you pass into the class). So essentially there we’ve created a constructor. What about with callback functions like jQuery’sready()‘? Well what we’d need to do is instead of firing the constructor function when the class is created we return the function ready for jQuery or your respective JavaScript library of choice function to call its callback:

var MyClass = function(v)
{
    function constructor()
    {
        document.write(v);
    }
       
    return constructor;
};

$( document ).ready( new MyClass( 'foo' ) );

And rejoice!

Where have comments gone?

Good question my old fruity. I'm now sticking any post discussions on Google+. Why? Well simply it's better. WordPress's comment system isn't very elegant and nor are ones like Disqus or Livefyre, so to save hassle I've just shipped them off to a social network, like a real boss.

Search

My social skills

Latest blog posts

  • Loading posts...

Subscribe in a reader

Latest tweets

  • Loading tweets...