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.




