JavaScript tutorial:
Object constructors

A common way to create an instance of a JavaScript object is use the new operator. It invokes the object's constructor (which initializes the object) and returns a reference to the object.

MyName = new String("Ian Rogers");
document.write(MyName);

You can use the Function constructor to create functions without a name, anonymous functions. You employ this technique whenever you need to construct a function dynamically, "on the fly". An anonymous function can be assigned to a variable.

isBetween = new Function("a", "b", "c", "if((a>=b)&&(a<=c))return(true);else return(false);");

document.write(isBetween(5, 1, 10));
document.write(isBetween(15, 1, 10));

To run the code, paste it into JavaScript Editor, and click the Execute button.

In the example above, the anonymoys function evaluates if the value of the number a falls between b and c, and returns true if it does, or false otherwise.

"a", "b", and "c" are parameters. Each parameter in the list in enclosed in quotes.
Lastly, the body of the function is enclosed in quotes.

Below is a traditional way of writing a function to do the same thing.

function isBetween(a, b, c)
{
    if((a>=b) && (a<=c)) return(true);
    else return(false);
}

As an exercise, write a function isPointInRect(x, y, top, left, bottom, right); to calculate if the point x,y falls within the rectangle denoted by the upper-left and lower-right points: top, left, bottom, right. When you are finished, convert the function into an anounymous one.

Creating constructors

To write your own constructors, you use the this keyword within the constructor to refer to the newly-created object. The constructor initializes the object.

In the example below:

The make7Table constructor creates a multiplication table for number 7
The size property is introduced to keep track of the number of elements
The value of each element is initialized
 

function make7Table(numElements)
{
    this.size = numElements;
    var cnt;
    for(cnt = 0; cnt < numElements; cnt++)
    {
        this[cnt] = cnt*7;
    }
}

// Use the constructor to create and initialize an array.
myArray = new make7Table(10);
document.write(myArray[5]);
document.write("This table has " + myArray.size + " elements");

To run the code, paste it into JavaScript Editor, and click the Execute button. myArray[5] retrieves the element with the value of 5*7 = 35.

Augmenting existing objects

Built-in JavaScript objects such as String or Math provide you with lots of functionality. You cannot, however, derive a new class out of it like in C++, C# or Java. What you can do is introduce new properties to existing objects.

The example below adds the baseSalary property to the Math object. From this moment on, the new property is available to the rest of the program.

Math.baseSalary = 50000;

function calculateSalary(bonus)
{
    return (Math.baseSalary + bonus);
}

document.write("Total salary: " + calculateSalary(10000));

Next