JavaScript Objects

A JavaScript object is a step up from a variable, which can contain only one value at a time, in that objects can contain multiple values and even functions. An object groups data together with the functions needed to manipulate it.

Declaring a Class

When creating a script to use objects, you need to design a composite of data and code called a class. Each new object based on this class is called an instance (or occurrence) of that class. As you’ve already seen, the data associated with an object are called its properties, while the functions it uses are called methods. Let’s look at how to declare the class for an object called User that will contain details about the current user. To create the class, just write a function named after the class. This function can accept arguments (I’ll show later how it’s invoked) and can create properties and methods for the objects in that class. The function is called a constructor.

function User(forename, username, password)
this.forename = forename
this.username = username
this.password = password
this.showUser = function()
document.write("Forename: " + this.forename + "<br />")
document.write("Username: " + this.username + "<br />")
document.write("Password: " + this.password + "<br />")

The function is different from other functions we’ve seen so far in two ways:
• It refers to an object named this. When the program creates an instance of User by running this function, this refers to the instance being created. The same function can be called over and over with different arguments, and will create a new User each time with different values for the properties forename, and so on.
• A new function named showUser is created within the function. The syntax shown here is new and rather complicated, but its purpose is to tie showUser to the User class. Thus, showUser comes into being as a method of the User class.


You may also like...