Javascript objects

Making an object

To make an object you need to first make a template. You then use this template to create all the objects. This example of a member system will need a template that has 3 variables: name, address and email address.

Here, we have made three different variables to hold each data item. Note the use of the this object to link the data with the current object. The first line allows us to access the members name by typing member.name, as you can see it is much easier to manage this data if all we need to do is type the object name (member) followed by the data field ‘.name’. The second and third line follow the same pattern allowing us to easily access the address, and email address of a member.

Instantiating an object

Now that we have made a basic object template we can make an object and give it values.

The code above shows how to make an object using the template we created. Notice how we give the object a name ‘pixelcode’. This means if we want to recall any information (e.g. the name) we need to type pixelcode.name . The object has been defined by adding all the information as parameters.

Viewing the information

The information can be viewed by suffixing the name of the object by the name of the field.

window.alert(pixelcode.name);

Changing the value of fields

To change the value of the fields of an object we can use similar code to displaying the object, only we write an assigment statement.

pixelcode.name = "new name";

Adding methods

To add methods to object define the function and then attach it to the object in a similar way to the fields.

This function checks to see if the name currenlty stored is less than 10 characters. Note the usage of the this object to refer to a variable not definied within the function, but refers to the fields of the object.