Skip to Main Content
Learning PHP, MySQL, and JavaScript
book

Learning PHP, MySQL, and JavaScript

by Robin Nixon
July 2009
Beginner content levelBeginner
526 pages
14h 24m
English
O'Reilly Media, Inc.
Content preview from Learning PHP, MySQL, and JavaScript

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 16-5 shows a constructor for the class User with three properties: forename, username, and password. The class also defines the method showUser.

Example 16-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>

The function ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Web Database Applications with PHP and MySQL, 2nd Edition

Web Database Applications with PHP and MySQL, 2nd Edition

Hugh E. Williams, David Lane
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 9780596803605Supplemental ContentErrata Page