Intro to Objects in JavaScript

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.

Firebug: The JavaScript Debugger

JavaScript is a core language of many web developers and a necessary component for any modern web application; therefore having an excellent JavaScript debugger and knowing how to use it effectively is key to fixing bugs faster. Fixing bugs faster also makes you a happier software developer!

I recommend Firebug, which is a JavaScript debugger, a real-time HTML, CSS, DOM, and JavaScript editor, and a network monitor.

Logging

One of the most useful features are the logging functions through console.log which can simply be used to output a string or object:

console.log('Testing log output: ', myObject);

This will output your message and the full object available for inspection in the Firebug console tab. In addition to console.log, there is also console.warn, console.error, and more. See the Firebug documentation for more info.

Be careful to remove the statements from your code before deploying it, because your users won’t have Firebug installed, and JavaScript will then fail when it tries to output to the console object. Also, you certainly don’t want users to see your debug output.

firebug logger
console.log in action

Breakpoints

Pausing scripts to investigate the system at a current point in time can be very valuable in solving bugs. To use the breakpoint feature click just to the left of a JavaScript line. This will set a breakpoint and make a red dot appear.

You can also add a conditional breakpoint by right clicking on a line number. Now the program will only pause under your specified condition.

firebug breakpoint
Setting a breakpoint

JavaScript Errors

Firebug will print out JavaScript errors with the corresponding file and line number. An absolute must for any JavaScript development.

firebug javascript error
A JavaScript Error

Those are the key feature I use most often, but there are many more JavaScript features in Firebug, including stack traces, watching expressions, profiling and viewing events.

Download Firebug now.