PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 6, Writing JavaScript Classes with Prototype

Declaring Classes

To create a new class with Prototype, the Class.create() function is used. This method accepts an object as the first argument, with each element of that object corresponding to a class method. The created class is returned from the call to Class.create().

Listing 1 shows an example of creating a new class called Person. An instance of this class represents a single person. I will build on this particular class as we continue through this article.

This class declares one property (name), in which the person's name is held. It also declares two functions; one for setting the name (setName()) and another for retrieving the name (getName()).

Listing 1 Creating a basic JavaScript class (listing-1.html)
<html>
    <head>
        <title>Creating a Basic JavaScript Class</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            var Person = Class.create({
 
                name : null,
 
                setName : function(name)
                {
                    this.name = name;
                },
 
                getName : function()
                {
                    return this.name;
                }
            });
 
            var me = new Person();
 
            me.setName('Quentin Zervaas');
 
            alert(me.getName());
        </script>
    </body>
</html>

Declaring the name property is not required (you can just assign directly to the variable to create it), but doing so makes it clearer that the property exists.

One important facet of creating classes in this manner is you must remember that each function is an object element (the first argument to Class.create()), which therefore means you must separate each element by comma. Think of it as Class.create({ function1, function2, function3 }).

As you can see in Listing 1, once the class has been declared we instantiate it using the new keyword, just as you would with most other OOP languages.

In This Article