Class and Object definitions in JavaScript

A developer friend of mine emailed me with a question about Classes in Javascript:

Don’t suppose you have any literature or anything I can look at in regards to the correct structure for a javascript class (in node.js)?
I have looked all over the shop and found various different ways of doing it but am having problems.

My emailed response

Classes don’t exist in Javascript (yet), at least not natively. There is some work on EcmaScript / that suggests they might but, in short:

Javascript is lexically scoped and functions are ‘1st class objects’.

You can declare and instantiate objects in many ways but the most familiar might be  like this:

function foo(bar){ = bar;

var myFoo = new foo('oh hi there');

Where you’d normally use the term ‘class’, it’s implied in Javascript, as above for example,  but not explicit. There are also many different ways to approach this. Javascript does not support access levels (private, public, protected etc) natively, so you have to follow a coding style that will have the same effect.

There  many different patterns you can use, but different patterns work well for different problems and you don’t always want to use the classical (class based) style, you can do things differently in Javascript and utilise the flexibility of the language to your advantage.

Some things worth reading about:

Read mostly everything Douglas Crockford writes: (and get his book on Javascript – The good parts). Although I disagree with some things he says about coding style, it’s all relevant even though it was written a while ago.

Learn these

Prototypal Inheritance

 Javascript scope

Javascript closures

Object Literals


Module pattern

That should be enough to get you started!


Interesting content, it makes work less ‘work like’!

I just finished working on the first release of this website (above) for Peter Grundy, with Further Creative

After discussing with the user experience expert and designer, I  faced the usual development decisions. I chose some solutions which use technology that I’d not employed in anger on many projects before. With Peter’s content being heavy on the visual side, delivered via Flickr, my decisions were largely driven by how well we could present his work,  over any potential SEO ranking.

I don’t remember enjoying working on content that was as stimulating and interesting as the work that Peter creates. Luckily Further allowed the user experience expert, designer and myself enough time to try and achieve what we set out to do and I think this first release is very close to getting there.

Working in a good team always makes work more enjoyable, and the client is always part of a wider development team. In this case the team was great and the content we were working on was inspiring.

I hope it’s not too long before I get to work on the same kind of project again!