Classes in JavaScript

Published on October 10, 2010 | Filed Under JavaScript

One of the most frustrating things about JavaScript (besides browser compatibility) is that there is really no way to define a class. That is, not without a little counter-intuitive work.

For today’s lesson, we’re going to take a theoretical car and simulate a trip down a bumpy road. If all four tires survive the trip, we’ll have a successful trip. If not, our trip will have failed.

Declaring the Class

Declaring a class in JavaScript is a lot like declaring a function in JavaScript.

function Car()
{
}

In fact, declaring a class in JavaScript is exactly like declaring a function in JavaScript.

Data Members

For Reference Data Members are also known as Fields, or Variables.

Our car is going to need a data member, which holds an array for all of the wheels. This is the same theory as creating a class in any other language and, luckily for us, it’s just continuing on with your function.

function Car()
{
  var Wheels = new Array(4);
}

As you can see, we now have a function with a data member within it.

Try to keep in mind that there are no “Private,” “Public,” “Protected” or “Friendly” access specifiers on your data members. These don’t exist in JavaScript. What you have instead are two ways of declaring your variables.

Let’s pretend like I wanted the car’s top speed (in MPH) and MPG.

function Car()
{
  var TopSpeedMPH = 500;
  this.MPG = 23.7
}

The member for top speed will only be accessible within our class and the member for MPG will be able to be accessed from an object of our class.

Just to throw in a fun contradiction: We are unable to do this with our current Wheels object. I haven’t come across a definitive answer as of yet, but it appears that creating objects (as opposed to system built-in keywords,) forces the object to have a private access specifier.

Methods

Methods are a bit odd in JavaScript, because other languages don’t typically allow you to create a function data member. That is, variables often only hold results. There are ways, in languages such as C++, to have a variable hold a reference to a method, but there’s usually no reason to do this. JavaScript is just funny like that!

To showcase how to create “private” and “public” methods, we’re going to ask our car class if it had a successful trip and it will make the trip by itself.

function Car()
{
  var Wheels = new Array(4);

  var AttemptTheTrip = function()
  {
    for(i = 0; i < 4; i++)
    {
      Wheels[i] = Math.floor(Math.random() * 20);
      if(Wheels[i] != 1)
        Wheels[i] = '';
    }
  }

  this.SuccessfulDrive = function()
  {
    var results = '';
    AttemptTheTrip();
    for(var i = 0; i < 4; i++)
      results += Wheels[i];
    if(results == '')
      return true;
    else
      return false;
  }
}

According to this bit of code, our class now has two methods added: AttemptTheTrip (which is considered "private", since it has a "var" declaration) and SuccessfulDrive (which is considered a "public" method because of the "this." declaration, and it returns a Boolean value.)

I don't need to explain how methods work, but I will only point out one key line of this entire block (from the SucessfulDrive function):

  AttemptTheTrip();

The importance here is that, in some languages (C++/C#/Java), you can access neighboring methods within the same class by using the this object. This is not the case within JavaScript. The this object holds a different meaning, so please try to break out of that habit, if you've gotten yourself into it.

Calling Your Class

Now that we have our car ready for our trip, the only thing left to do is go on our trip! You create the class, just like we did for the Array object and you access the members and methods within, just like any other language.

function DriveCar()
{
  var varCar = new Car();
  if(varCar.SuccessfulDrive())
    alert('Your trip was successful');
  else
    alert('Your trip was unsuccessful');
}

We have now created a new instance of our Car class, called the SucessfulDrive method and processed it, just like we would with any other class out there!

I really hope this has helped to shed some light on how classes work within JavaScript. It's a strange concept to grasp, but once you've done a couple of classes of your own, it will really just become second-nature.

~Derek Torrence

Leave a Reply

*