Object Oriented Programming for Javascript Dummies - Part 1
Tuesday, 30th October 2012, 16:01
One thing quite a lot of programmers just don't get is OOP, aka Object Oriented Programming. I'm not sure why, it's very easy, there really isn't much to it once you grasp the thing. But many don't, which is a shame because even in a language like Javascript that lacks proper classes and inheritance, it is an extremely useful concept.
So here we go, the first of a two part tutorial that should take anyone who understands the basics of programming, and get them to grasp the basics of OOP.
First, a history lesson, we need to understand the roots of object based programming. If you don't know why you should do something, you'll never really know how to do it properly.
We'll be using a bit of C/C++ here, just because that's where a lot of concepts have their origins, even if they might not have been the first examples. C shares some syntax with Javascript, so you should be able to follow it easy enough.
Variables
The earliest computers had states, which evolved into registers. These were (and still are) like hands used for counting on, with a limit as to how high you could count on them. At some point though, you run out of hands and need to write down the numbers somewhere, which is were memory comes in.
On a slightly higher level of thought, we have a variable. This is an abstract concept, sometimes they only exist for a short period of time and are assigned to a specific register in the CPU. Other times they are stored in memory locations, and often they move backwards and forwards between memory and the registers.
But we all know that one variable stores one value, whether that be a number, character or string.
char *strName = "Minna";
int intAge = 14;
char *strBreed = "Finnish Lapphund";
char *strAnimal = "Dog";
But obviously in this day and age, having four variables to represent one thing, is annoying. Not least because when you call a function you have to pass an awful lot of parameters:
printInfo(strName, intAge, strBreed, strAnimal);
So, in the C language, someone decided to use structures.
Structures
A structure is a collection of variables stored as members of an object, so the above becomes:
struct animal
{
char *strName;
int intAge;
char *strBreed;
char *strAnimal;
};
struct animal Minna;
Each of our original variables is now a member of the structure. Putting aside the fact we just created a structure but haven't assigned any data from it, just look at what we pass to a function now:
printInfo(&Minna);
Because structures in C are stored in contiguous memory, if you pass the address where the start of it is stored, it's very predictable to know where each member of the structure is as an offset from the start address.
Let's Go Javascript!
At this point, we can stop with C in our history lesson and move on to Javascript, where a lot of people spend their time these days. Our object above in JS becomes:
var objMinna = {
strName: "Minna",
intAge: 14,
strBreed: "Finnish Lapphund",
strAnimal: "Dog"
};
And obviously we can call a function with it like so:
printInfo(objMinna);
There is always a danger, especially in a language as fast and loose as Javascript, in which you can call a function with the wrong arguments. Say we like the function name printInfo so much, we want to use it whenever we need to print some info about our object. But clearly here we can only do it if the object has the same format as above, and we can't have multiple functions called printInfo, can we?
We could probably do this if we were still in C, it is after all a strongly typed language, but Javascript flies loose in this world.
Member Functions
Actually, in JS, we can because one of the beauties of OOP is functions and objects are not separate entities, they become one entity. So we rewrite our above object in a different way:
function animal(strName, intAge, strBreed, strAnimal)
{
this.strName = strName;
this.intAge = intAge;
this.strBreed = strBreed;
this.strAnimal = strAnimal;
}
animal.prototype.printInfo = function()
{
console.log(this.strName + " is " + this.intAge " years old");
}
And now we have an animal object that we can use like so:
var objMinna = new animal("Minna", 14, "Finnish Lapphund", "Dog");
objMinna.printInfo();
Since the printInfo function is a property of the animal object, we can call it on that object. All functions are passed a "this" parameter which refers to the object they are operating on. If no object exists then this refers to a single global object, because it always has to refer to something.
What You Have Hopefully Learnt
In this first of two parts, hopefully you now know why we use objects and have an insight into possible uses for them. Basically, if you have a variable or a group of variables which work with specific functions, you should be grouping them all up into an object.
Here are a few things I use objects for, and this excludes jQuery client side stuff which heavily relies on OOP based objects:
- Information about a user, with functions for getting and setting parameters such as their index in databases, permissions on what they are allowed to do, along with functions for attempting to authenticate them
- Creating and maintaining a connection to a database, and executing commands on that database
- Storing information which is written to and from XML
- Caching database query results, passing through queries when they miss, returning cached results when they hit
- Delivering specific webpages
Some of these are essentially flat objects, with no inheritance. What is inheritance I hear you cry? Well that is what we'll talk about next week in the second and final part.