he Prototype home page
Prototype is a pretty big framework, however. No one article can cover it all. So this discussion covers just a few key features. For a deeper understanding of the whole framework, dive into the source code. That's the best way to understand the nuts and bolts so you can modify it to meet your needs.
To use Prototype in your Web application, first download the latest version. (At the time of writing, it was version 1.4.0.) The only file you really need is prototype.js, and you just include it in your pages using a <script> tag as follows:
You already saw the $ function, which is a shortcut for document.getElementById. You can also pass more than one element ID to $. For the following code, the result will be an array that contains the requested elements:
<!-- HTML -->
<div id="firstElem">First element's content</div>
<div id="secondElem">Second element's content</div>
var elems = $("firstElem", "secondElem");
alert(elems.innerHTML); //displays "Second element's content"
Another really useful shortcut function is $F, which takes a form field ID and returns the field value:
<!-- HTML -->
<select name="language" id="language">
var langValue = $F("language");
alert(langValue); //displays "JS"
// Class definition
var Person = Class.create();
// Class methods
initialize : function(firstName, lastName, age)
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
toString : function()
return this.firstName + " " + this.lastName + ", " + this.age;
displayFirstName : function()
var myPerson = new Person("Alessandro", "Lacava", 30);
alert(myPerson.toString()); //displays "Alessandro Lacava, 30"
As you can see, the constructor is defined using (by convention) a method whose name is initialize. This example also defines two other methods: toString and displayFirstName. Of course, you can define as many methods as you need.
Using Prototype, you can also extend an existing class through the Object.extend method. It copies one object's properties and methods into another. The syntax is Object.extend(destination, source), where destination is the object that will be extended with the source's properties and methods.