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

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)
    { = name;
    getName : function()
Listing 3 Loading and instantiating the Person class (listing-3.html)
        <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>
        <script type="text/javascript">
            var me = new Person();
            me.setName('Quentin Zervaas');

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