Javascript and proper Classes

Javascript over the years has come on leaps and bounds, but it's still very deficient when it comes to proper object orientation with regards to classes. You can define classes after a fashion, but they're more for encapsulation than anything else, and the concept of inheritance, constructors etc, are AWOL. On the plus side there are numerous libraries available to mitigate this, sadly none really stands out as 'the' solution, but this is the best one I've tried thus far.


Although I use this exclusively within a browser environment, I'm going to run through this using NodeJS, just because it's easier to demonstrate from the command line. First we need to install jsClass, in a web page this is simply done with;

<!-- JSClass support -->
<script>JSCLASS_PATH = 'js/jsclass-4.0.5/min'</script>
<script src="js/jsclass-4.0.5/min/loader-browser.js"></script>
<script src="js/jsclass-4.0.5/min/core.js"></script>

However in a Node environment we can get away with;

npm install jsclass

Then, let the fun begin, we now have access (essentially) to proper object orientated Javascript with proper class handling. For example;

var JS = require('jsclass');        // include the libs here
var CLASS = CLASS || {};            // we like namespaces

var output = JS.require('JS.Class',function(Class) {
  CLASS.Dino = new Class({
    initialize: function(name) { 
      this._name = name; 
    show: function() { 
      console.log("I "+this._name+", Peekabo"); 
    hide: function() { 
      console.log("I "+this._name+", I no see you"); 
>var barney = new CLASS.Dino('Fred');
I Fred, Peekabo
I Fred, I no see you

So this is all simple stuff, it's really the extras that make it worthwhile consider;

var output = JS.require('JS.Class',function(Class){
  CLASS.Raptor = new Class(CLASS.Dino,{
    initialize: function(name,teeth) {
      this._teeth = teeth;
    show: function() {
      console.log('I will eat you with '+this._teeth+' teeth');
> var izzy = new CLASS.Raptor("Harry",100)
> izzy.hide()
I Harry, I no see you
I Harry, Peekabo
I will eat you with 100 teeth

Couple of things to note, in particular that callSuper automatically passes all arguments up the chain, so there's no need to specify. Also available is support for things like deferreds, observables and a number of useful inbuilt structures. In general, quite a nice level of encapsulation that's relatively easy to work with .. just wondering why it doesn't get more coverage .. maybe everyone is waiting for ECMA 6?

More here with documentation.