Introduction to Object Oriented JavaScript

Categories Articles

For some reason there’s a tendency in the IT industry to take the view that if you’re not using Object Oriented Programming (OOP) methods, then  you’re not a “real programmer”.   That is actually a somewhat silly stance to take, because there are many situations where OOP is not the most appropriate way to deal with a problem.  This is the flaw in languages like Java which force OOP into every programming task whether you need it or not.

JavaScript (which has almost nothing to do with Java) is quite a different language.  It provides almost unlimited freedom and versatility, with reduced complexity in most areas.  Unfortunately there are some things that are more complicated in JavaScript because of the freedom it tries to give you.

Why OOP isn’t always suitable for every task is that it adds more complexity to a program and will often involve extra steps, more work, and more things that can potentially go wrong if you’re not paying attention.  But OOP also can provide a lot of advantages if it’s used in situations where it is appropriate.

The most important advantage OOP can offer us is replication, which means we can clone an object and re-use it multiple times in the same program, whenever we need it.  The implied complexity, and the fact that JavaScript isn’t built from the start to be an OOP language (thus adding more complexity), is one of the reasons why OOP represents the final frontier for many fledgling JavaScript programmers before they earn their wings.

OK, it’s hard, but it’s not that hard

Before you start thinking the concept of Object Oriented JavaScript is too much for you, consider that you’re already using OOP even if you’re not aware of it.   Purists might disagree, but I think it is fair to say that if you’re already using HTML and CSS, and you’ve occasionally used JavaScript to manipulate HTML elements on a web page, then you’re already an experienced OOP programmer.

Every HTML element on a web page is actually an object.  They all fit into the Document Object Model (DOM) hierarchy, which means they have a defined class, defined properties, and defined inheritance.  Unless you explicitly set a property value, all objects will use their default property values.  When you write a CSS instruction, what’s really happening is you’re using a method to modify one or more property values of a class.

Every time you write a HTML instruction, you’re create a new instance of a class.  And as you would certainly already know, you can create your own classes based on the pre-defined class of each object type (for example, you can create <h2 class=”subheading”> which might have very different properties from the original class it was created from).  You may specify that H2 objects with this class will have a different color and size from the regular H2 objects.  And you can re-use those modified objects as often as you like.  The original H2 object is an object template and your new class is derived from the template class.

So yes, OOP isn’t easy, but you’re probably already doing it, so what is there to be afraid of?

The next level: creating your own objects

Working with built-in DOM objects is too easy.  You need more challenges.  Making your own objects is the first step to a higher level of OOP.

With all that preamble, you’re probably expecting that creating an object is a big deal requiring a lot of complex code.  Certainly if you’ve ever tried creating custom object classes in a language like Java or C#, you’ll be expecting to create a lengthy class constructor.  Here’s how we do it in JavaScript:

Well that was anti-climatic, huh? What we did there was we created an empty object of class “myObject”.  Obviously empty objects are boring, because they don’t do anything except take up space in memory.  To be useful, an object needs to have contents.  Let’s consider a more practical class:

The above shows an object called objAlien which has all these different properties (ordinary variables) and methods (function) defined within it.  Technically, then, you could also consider an object to be an array of variables and/or functions.

Using objects in a program

Once an object has been defined, you can reference it in your programs.  In a game, you’d have multiple aliens, but writing code for each individual alien would make the program too cumbersome.  A better way is to create an array to store all the aliens, and then use the alien class to create new aliens.  For example:

This code would make 20 slimy green aliens placing them 110 pixels apart (so we could guess from this that the image used to store the alien is 100px wide, and there’s a 10px margin between each alien).  Obviously, of course, this isn’t a good way to implement a game in JavaScript because there are better techniques, but this article isn’t about making games, it’s about creating and using objects.

Objects don’t always have to be added using the new keyword.  Here’s a sample of code from a project where an object sets its own properties using the values of another object:

 

Here we can see a really complex way of using an object, where the object’s values are passed to the attr property of the R object.  If you’re familiar with JSON (JavaScript Object Notation), then you may think the first part of the example is using JSON with syntax errors, but in fact it’s not JSON code.

The reason the variable names, except fill, are quoted is to prevent JavaScript from processing the minus operator in the variable names (which are CSS properties).  Since that program was written, changes were made to allow CSS properties like font-family to be written as fontFamily, but this legacy code hasn’t been adapted to take advantage of that change.

Why use objects?

Objects are best for situations where you need to make multiple instances of something, or where you need a simple way to group data related to something of a particular type.  In the game example above, we can see that it was possible to create multiple copies of the objAlien object, but we could also manipulate properties of the object after we added it, which in the case of the example was the x property.

When not to use objects?

You shouldn’t use objects if you project doesn’t really need them.  It’s pointless to over-complicate your programs without a good reason. If your program is designed to do something simple,  OOP techniques shouldn’t be required.

Why JavaScript Objects are easier to create than Objects in other OOP languages

In languages like Java and even Visual Basic, creating objects is a big task.  This is because you need to create a class template (or use an existing one) to base your object on before you can define it.  That isn’t necessary in JavaScript because we’re given a simple construction technique (objectname={…}).  Objects in JavaScript can also include any type of variable, including arrays, and type declarations are non-existent.  Return values are optional.

Whether it is a good thing or a bad thing is a matter of some debate, but JavaScript programs also won’t fail if you attempt to call up a property value that does not exist.  For example, if you typed:

You would quite rightly expect the above line of code to put 5 inside the element with ID “par1”.  But if you were to type something like:

You would not see the alien’s favorite flavor, you would see undefined appear in par1.  For most applications this would not be a problem, but for some it would be.  In those cases, you need to be prepared for that and write code that tests for valid values before relying on them.

One way to test for this is:

That response is a bit extreme, but you get the idea. Notice we are testing for “!==” and not “!=”, which is an easy thing to get confused about.  Here’s another way to do it:

Same thing, different way.  You can also add properties to objects after creating them.  You can do that this way:

Obviously you can also change the values of the properties in the same way.  To remove the favoriteFlavor property from the object, we’d need to do this:

There are very few situations where this would ever be necessary.

Making Objects more re-usable

You probably noticed the biggest potential problem with creating objects, which is that if you wanted to have different types of aliens, you’d need to make the objAlien.type property an array.  But there’s another way, which is better.

This technique is called object prototyping, which means you make a basic template for the object but don’t fill in all the details.  Here also, we’re getting closer to the real way to add objects to a game.

You can see now the methods of the object are defined, but most of the properties are not defined.  Also instead of being a simple variable, the object declaration is now wrapped inside a function, and that’s because it’s not actually an object yet.  It’s just a prototype of an object, describing how to create the object without actually creating it.

So now to actually create objects based on the prototype we could do this:

This is the same as doing this:

Because we created a prototype, we didn’t need to do it the second way, and declaring different types of aliens with different speeds, number of arms, weapons, and starting positions is much easier.

What next?

This article was an introduction to Object Oriented JavaScript, which hopefully demystified the subject and made it seem less intimidating.  We covered all the basics including how to create simple objects, how to add, remove, and modify properties, how to declare and use methods, and how to use prototyping to make objects easier to re-use.  But there’s still plenty more to learn, so now that you have a good starting point, you’ll be able to approach any tutorial or lesson on more advanced OOP with confidence.

Inspired Mag Team

We always try to come up with high quality and well-researched content in order to inform and inspire the creative web community.