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!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s