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.

Example 15-5 shows a constructor for the class User with three properties: forename, username, and password. The class also defines the method showUser.

Example 15-5. Declaring the User class and its method
<script> 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 />") } } </script> ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.