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'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: var MyClass = function(v) { function constructor() { document.write(v); } return constructor; }; $( document ).ready( new MyClass( 'foo' ) ); And rejoice!

© Ahmed Nuaman, all of my code and stuff is available under a 'Attribution-ShareAlike 3.0 Unported' license, however my clients own their respective copyrights.

Contact me

07811 184 436
London & Kent, UK