PhpRiot
Download This Article
Download this article or the entire “Eight Weeks of Prototype” series with all listings and files.




More information
Related Books
JavaScript: The Good Parts

JavaScript: The Good Parts

Most programming languages contain good and bad parts, but JavaScript has more than its share...

jQuery: Novice to Ninja

jQuery: Novice to Ninja

jQuery: Novice to Ninja is a compilation of best-practice jQuery solutions to meet the most...
Browse Articles
Ajax (4), Amazon (1), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (8), onbeforeunload (1), OOP (1), PHP (35), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (2), SimpleXML (1), Smarty (5), SOAP (2), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (7), Zend_Loader (1), Zend_Registry (1), Zend_Search_Lucene (1)

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

Saving and Accessing Classes

My own personal preference when saving classes is to save each class to a separate file, using the filename ClassName.js.

Note: Additionally, when I want to namespace (that is, group classes into separate packages) I will name the class PackageName_ClassName and save the file to PackageName/ClassName.js.

Therefore, re-working the Person class into a separate file would result in the code in Listing 2. We can then load the class file and instantiate the class as shown in Listing 3.

Listing 2 Declaring the Person class in an external file (Person.js)
var Person = Class.create({
 
    name : null,
 
    setName : function(name)
    {
        this.name = name;
    },
 
    getName : function()
    {
        return this.name;
    }
});
Listing 3 Loading and instantiating the Person class (listing-3.html)
<html>
    <head>
        <title>Loading and instantiating the Person class</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
        <script type="text/javascript" src="/js/Person.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            var me = new Person();
 
            me.setName('Quentin Zervaas');
 
            alert(me.getName());
        </script>
    </body>
</html>

You should always be declaring your classes in external files and not inline in your HTML. In fact, you should almost never include any JavaScript code in your HTML files – I've done so in these examples to simplify matters, but in the seventh article in this series I'll discuss this matter further.

In This Article


Tagged in ,