Object orientation in javascript

One of the hardest things for any begginer javascript developer is how to do object orientation correctly. Specially to those coming from other programming languages. It was hard to me also. I know, many say it’s a prototyped language, you have to have a different approach, etc. But even with this approach, some basic concept are crucial to any developer with some expertise. You have to be able to organize the code in classes, you have to be able to inherit classes, you have to be able to call the super class code and expand it, you have to be able to have public and private variables, initialize class variables, and you need decent polymorphism. That’s not asking too much, This is the minimum of any modern language.
It was by searching on how to do this “minimum” in js that I realize that one needs to search a lot, read a lot, in different places to do just this “minimum”.
In this post I summarize 3 techiques to apply oo concepts in javascript. The objective is that any begginer can at least start developing and learn with time the js way of programming.
To those who want to go deeper, I recomend the excelent book: The Principles of Object-Oriented JavaScript by Nicholas C. Zakas

Example download: OOJS-enUS.tar.gz

All techiques use the same example, based in a simple application that calculates the 4 basic operations, with this base HTML:

So it looks like this:

OOjs

Techique 1 – using prototype and new

JSFiddle: http://jsfiddle.net/59c7mso5/

Technique 2 – Module Pattern

Module Pattern is a pattern for organizing code in modules which can contain multiple classes, put together in the same context. To this example we will use one class per module.

JSFiddle: http://jsfiddle.net/u14j9ydc/

Technique 3 – AMD – Asynchronous Module Definition

This techique, is an extension of Module Pattern, loading modules asynchronously. This isn’t a native js feature. It’s implemented by some libraries.
On this example we’ll use one of the most used (Require.js), putting each class in a different file.

JSFiddle: http://jsfiddle.net/q7bdn31a/
(the code below was slightly adapted for the site)

We’ll use this folder structure:

jquery.min.js and require.js are the libraries. app.js is the configuration file for require.js:

In index.html file we’ll to a slight modification. The only library we’ll need to declare is require.js
After that the library with handle the task of loading others:

main.js

operators.js

randomizer.js

operations.js

Leave a Comment