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 / JavaScript.next 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){
    this.bar = bar;
}

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

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.

http://www.crockford.com/

Learn these

Prototypal Inheritance

http://javascript.crockford.com/prototypal.html

 Javascript scope

http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

Javascript closures

http://blog.morrisjohns.com/javascript_closures_for_dummies

Object Literals

http://www.dyn-web.com/tutorials/obj_lit.php

Currying

http://www.dustindiaz.com/javascript-curry/

Module pattern

http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

That should be enough to get you started!