Object-Oriented JavaScript
A demonstration of how Class Definitions (Prototypes), Fields, Constructors, and Methods are written.
©2007, Bob Beeman
Updated 2007-08-19 @ 14:50 EDT (UT-4)
Read More www.bee-man.us Important Notice

JavaScript (also called ECMA-script) is (or at least can be used as) an Object-Oriented Language. More correctly, JavaScript uses Prototype-Based Programming, which is like Object Oriented programming except that instead of classes, instances are created by cloning existing objects, which are used as prototypes. Thus, unlike Java or C++, in which Class Definitions are written and instances created from the Class Definitions, JavaScript uses functions as prototypes and the "new" keyword is used to create instances. Also in JavaScript, adding a field or method to one of the instances of a given prototype adds that field or method to the prototype and ALL of its instances, including those yet to be created.

This page is just a quick description of some useful techniques. For a real tutorial, see the links below under "Read More".

Functions and Prototypes.

When you write a JavaScript function, you are really writing a prototype (almost a Class Definition). Fields within objects in the class are defined with the "this" key word in the definition, and are accessed in the same manner. Methods can either be defined by linking other functions to the constructor, or by writing "inner" functions within the main (Class Constructor) function.

Assuming that MyCalculator() and MyCalculator2() are JavaScript functions that have already been written, objects (Instances of a Class or Prototype) are constructed by using the "new" keyword as in the following:

    theCalculator  = new MyCalculator;
    theCalculator2 = new MyCalculator2;
which creates a new instance of the "MyCalculator" class with the name "theCalculator" (on the left below) and a new instance of the "MyCalculator2" class with the name "theCalculator2" (on the right below).

If necessary, statements would be added below the constructor statement to initialize the fields in the new object.

    someObject = new MyObject;
        someObject.someField = 3.5;
Note that even if if someObject didn't initially have a field called "someField", it will after the second statement, and so will MyObject and all objects created as new instances of "MyObject", even if they were created before the execution of the second statement!

Demonstration Calculators.

Below are two simple calculators (theCalculator using external method functions and theCalculator2 using "inner" method functions) that allow you to set a value into a text box and enter it into a field in an object that corresponds to the calculator class. You can also Decrement, Increment, Divide by 2, Multiply by 2, or round the single field to the nearest integer.

The nice thing about the use of "inner" method functions is that the objects created in this manner are self-contained, and you don't have to worry about name conflicts.

Snippets of code are shown beneath each calculator to give an idea of the differences between the two kinds of Class Definition. Do a "View Source" on this page to see the full details.

An instance of the "MyCalculator" Class/Function
which implements Methods via external functions.
  /*R. H. Beeman 2007-08-13 Mo
    This is the definition for the 
        MyCalculator class.
    It has one field: 
        num: a numeric variable.
    It has 6 methods, 
        implemented as external functions:
    Only 1 is shown.
        incr: Increments num by 1.
    var num = 0;
    this.num = num;
    this.incr = incr;

    this.num += 1;
    document.calc1.text.value = this.num;
An instance of the "MyCalculator2" Class/Function
which implements Methods via "inner" functions.
  /*R. H. Beeman 2007-08-13 Mo
    This is the definition for the 
        MyCalculator2 class.
    It has one field: 
        num: a numeric variable.
    It has 6 methods, 
        implemented as "inner" functions:
    Only 1 is shown.
      incr: Increments num by 1.
    var num = 0;
    this.num = num;
    this.incr = function(){
      this.num += 1;
      document.calc1.text.value = this.num;

JavaScript in the browser address bar.

One of the neat things about JavaScript is that you can paste single-line JavaScript commands into the address bar of your browser and press return. This will cause the JavaScript command to be executed! To see how this works, paste the following into the Address bar of your browser making sure to:

Then press return or hit the browser "reload" button and see what happens.
    JavaScript:var a = 361; alert("The square root of " + a + " is: " + Math.sqrt(a));

You can change the value of "a" in the above to find the square root of other numbers. Interestingly, you can save this, or any other such one-line JavaScript as a bookmark, so that it is available for immediate use from your bookmarks. Google "bookmarklet" for more info.

We will use this as a "quick and dirty" way to investigate the behavior and properties of some JavaScript functions, objects, and variables embedded in the source of this page.

Hint: Some browsers will reload the page if you hit the "reload" button with a JavaScript command in the address bar. Some will re-execute the JavaScript command. In the latter case, to reload the page you need to erase the JavaScript command first, so that the address bar is blank, then hit your browser's "reload" button.

The "arguments" variable in functions.

Every Javascript function creates a private variable called "arguments" which contains an array of the arguments used to call it. This page includes a function called testArgs() which contains the following code:

        var list = "";
        for(i = 0; i < arguments.length; i++){
            list += "Argument " + i + " = " + arguments[i] + "\n";
To see how the "testArgs" function works, paste the following into the Address bar of your browser and see what happens:
    JavaScript:testArgs("A parameter", 7, 42, "Another parameter", 16);
Pretty cool, eh? Try changing the parameters, adding a few, or eliminating some. Remember that parameters must be separated by commas.

Using the "arguments" variable allows you to write functions that accept an unknown number of parameters. Of course the code you write has to do something sensible with them.

Using the "arguments" variable in a function.

Here is a function, already encoded in the source of this page, that accepts a bunch of number parameters and creates an alert box containing the sum of the numbers:

    	var sum = 0;
    	var text = "";
        for(i = 0; i < arguments.length; i++){
            sum += Number(arguments[i]);
            if(i != 0){text += " + ";}
            text += arguments[i];
        if(arguments.length == 0){text += "no numbers";}
        text += "  =  "
        alert(text + sum);
So paste the following line into the address bar and see what happens:
    JavaScript:addItUp(7, 5, 3, 6);
Of course we know that 7 + 5 + 3 + 6 = 21, right?

Try doing the same and changing the number and/or values of parameters. The function should work with any number of parameters.

Then try pasting the following into the address bar and see if you can figure out what went wrong:

    JavaScript:addItUp(7, 5, 3, 6, "Yoda");
Hint: "NaN" stands for "Not a Number". As in "The sum of 7, 5, 3, 6, and 'Yoda' is Not a Number".

Finding values of Variables, Objects, or Fields of Objects.

Another thing you can do with JavaScript is find out the value of any object or any of its fields. For example, the JavaScript code for this page includes a global array variable called "myStr" which contains the name of 4 "Star Wars" characters as 4 string elements of the array. You can find out the values of these 4 string elements one-by-one by executing:


You can see the value of all of the strings in the array by executing:


And finally, you can find the value of the "num" field in "theCalculator" up near the top of the page by executing the following, which you should do after you scroll up to the left calculator and play with the buttons to set in some value:


Note that the value is always the value in "theCalculator". Change "theCalculator" to "theCalculator2" in the above to do the same thing for the "num" field in the right calculator above.

Finding the Type of Objects.

And finally, using the JavaScript operator "typeof" you can discover the type of any object as in the following examples:

JavaScript:alert(typeof myStr);
JavaScript:alert(typeof myStr[1]);
JavaScript:alert(typeof MyCalculator);
JavaScript:alert(typeof theCalculator);
JavaScript:alert(typeof theCalculator.num);

JavaScript:alert(typeof true);
JavaScript:alert(typeof false);
JavaScript:alert(typeof "May the Force be with you.");
JavaScript:alert(typeof 7);

More information.

Obviously, this page only touches on the rudiments of writing Object-Oriented JavaScripts. Google "Object Oriented JavaScript" or similar to find a bunch of tutorials on this subject.

One excellent beginning-level tutorial that I found on Object-Oriented JavaScript programming was written by Ryan Frishberg, at SitePoint:
JavaScript Object-Oriented Programming Part 1
JavaScript Object-Oriented Programming Part 2

For a discussion of prototype-based programming, as in JavaScript, Google that term or see the article at Wikipedia:
Prototype Based Programming

This page is copyrighted "freeware"
©2007, Bob Beeman

I make NO guarantee of any kind.
This page may contain serious errors.
Use this page entirely at your own risk!
Do not use this page for any illegal purpose.

Subject to the above, you may use this page and its included software yourself, copy and redistribute it, or even put it on your own website. I ask only that you not make any changes, and that if you reuse any of the code, make sure to list me as one of your sources.

My only reward for writing this is the 15 milliseconds of fame I receive from having my name here. Don't deprive me of that.

You can copy this page so that it works when you are not connected to the net by simply doing a "Save As" in your browser. In order to do this you will have to look at the features of your browser and decide to save the page as one of the following: