Object oriented programming in JavaScript

OOP paradigm is probably most discussed topic in JavaScript and most popular type of library extending the language. I believe that first approach to make JS object model more usable was made by Douglas Crockford, in 2002. 11 years have passed and honestly nothing remotely close to common OOP toolset has been offered. Inheritance, interfaces, visibility scope… all these tiny features that make OOP easier are still no there or are hacked in very peculiar way. I was already thinking we’ll have to wait another 10 or so years for popular browser to fully implement ECMA 2, and 3, and 5 to get these abstracts and private and so on to be generally available. Wait no more. Someone did amazing job bringing all the missing “keywords” into JavaScript way and in rather clean way. And wrapped as AMD. And faster than vanilla classes. Get ready to experience dejavu.

Dejavu package comes in two versions. Strict and loose, or better call them development and production. The development one does all the heavy checks of method signatures and full interface implementations. It makes library slow but hey, if you do not implement a method of an interface your tool should warn you. The loose version is suited for production. It’s extremely fast but the speed is gained by removing all the heaving checking. Thus if your class is missing a method of an interface it is implementing and you run your code with loose version of dejavu you won’t be warned. Code will execute and will work… or not.

Feature list is extensive. Dejavu provides syntax for:

  • concrete, abstract and final classes as well interfaces
  • working JavaScript instanceof for classes and new function instanceOf for interfaces
  • private and protected (visibility)
  • static members and constants
  • “super” for calling super (parent) implementation of methods, including constructor
  • verification of method signatures
  • context binding
  • freezing and unfreezing objects

It also lets you define singletons and do classes mixins but I hope no one uses these features.

Since dejavu homepage provides complete examples of all features I’m not going to duplicate the effort and write practically copy/paste tutorial. I’ll just borrow one of example classes:

Convinced? Go to dejavu homepage and improve your JavaScript OOP coding experience.

Author: Wojciech Szela

CSM, Consultant, Manager, Entrepreneur and Open Source Contributor. Scrum and eXtreme Programming practitioner. Evangelist of healthy work environment, high quality products, people development and team work.