The Module Pattern And Inheritance: A Better Way

Recently I blogged about how I like to build my JavaScript “classes”. I personally prefer the module pattern: it provides true encapsulation and doesn’t expose unnecessary methods and properties, which you get when you use the typical prototype pattern.

One of the downsides of it, I’ve been told, is that it doesn’t easily allow to build classes that you can inherit from. That is true if you mix the styles, specially if you want to inherit from a class that is built this way. But if you are willing to use this technique throughout all the inheritance chain, I will demonstrate that it provides a much more powerful and sane way of doing inheritance.

One of the fallacies of using inheritance in JavaScript in the typical prototypical way - and in the model of most OO programming languages I know - is that inheritance, as it is, is a leaky abstraction. Most of the time you have to be aware of some of the implementation details of the super class to be able to inherit from it properly. For instance, since the entire prototypical chain uses the object that is bound to this, you have to be careful that you don’t override any of the properties that are being used down the chain.

For instance, if you are inheriting from Node.js EventEmitter pseudo-class, you have to be careful to never override any of the properties it initializes and changes.

This happens because the cat object is being used like a property global namespace for storing all and every property of this object. Global namespaces tend to become overcrowded and clashes happen if there is no alternative.