Thursday, January 5th, 2012
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:
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:
{
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’s ‘ready()‘? 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:
{
function constructor()
{
document.write(v);
}
return constructor;
};
$( document ).ready( new MyClass( 'foo' ) );
And rejoice!