Object-oriented programming review

Objects can be used in JavaScript to group together data and the functions that need to work on that data.

Defining objects

Objects are defined as functions in JavaScript. You can add properties to that function by specifying them in the body of the object declaration, preceded by the 'this' keyword. Once defined, an object can be instantiated using the 'new' keyword. The properties can then be accessed using the familiar dot notation.

Passing values to the constructor

Properties can be set when an object is instantiated by specifying the value of the in the argument list for the object. For example, the following code will create an exampleObj object called theObject, and initialise its exampleVal property to the string "the value":

function exampleObj(a_value)
{
this.exampleVal = a_value;
}

var theObject = new exampleObj("the value");

Adding methods

Methods are added to objects in exactly the same way as a property. However, before assigning a method to an object, it has to be first defined as a standalone function. For example, assuming that a function has already been defined called theFunction(), we could define an exampleObj to use that method:

function exampleObj(a_value)
{
this.exampleVal = a_value;
this.exampleFunc = theFunction;
}

Objects as properties of other objects

You can also use other objects as properties of a new object. Objects are assigned to new objects in the same mannor as properties and methods are assigned..

Using objects

Generally, you will find that objects are best used when you need to organise a great deal of similar information. Objects force a consistency in the data, which then makes it easy to add new methods to manipulate that data.