Intro to Objects in JavaScript

Wed, Oct 21, 2009 2-minute read

Despite what you might think, JavaScript supports programming in full object oriented style including inheritance, encapsulation and polymorphism. But before we dive into all those topics I’m going to start with the basics and demonstrate how to create and use a simple JavaScript object.

Lets say you have a web application that needs to track how long an AJAX request took. If you were writing it in Ruby, PHP or Python you’d have a timer object that you can start() and stop() and a seconds() method to get the number of seconds that passed between calling the first two methods.

To build this in JavaScript we first create our constructor:

Timer = function() {
  var seconds_passed = 0;
}

Here we are creating a Timer object with a private seconds_passed variable. To create this object we we simply create a new timer:

var elapsed_timer = new Timer();

This timer object now needs some public methods. We can attach a public method by using this.method_name:

Timer = function() {
  var seconds_passed = 0;

  this.start = function() {
    // implementation here
  }
}

Our Timer class now has a start() function. Additional public methods can be added in the same way.

To add a private method, don’t define it with the this keyword but instead create a regular function inside the class:

Timer = function() {
  function increment() {
    // implementation of private method here
  }
}

Now we have a Timer object with a public start method and a private increment method. The rest of the class is fairly simple, so lets jump to the finished solution.

Complete Example

Timer = function() {
  var timeout_id = null;
  var seconds_passed = 0;

  this.start = function() {
    increment();
  }

  this.stop = function() {
    clearTimeout(timeout_id);
    timeout_id = null;
  }

  this.seconds = function() {
    return seconds_passed;
  }

  function increment() {
    seconds_passed++;

    timeout_id = window.setTimeout(
      function() {
        increment();
      }
      , 1000
    );
  }
}

var elapsed_timer = new Timer();
elapsed_timer.start();

// do some stuff

elapsed_timer.stop();
alert(elapsed_timer.seconds());

There you have it. A simple JavaScript timer to keep track of time.