O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.2. Creating Classes in a More Object-Oriented style

Previously we saw how to create classes in raw JavaScript. The good news is that by using Prototype, we may do this is a more streamlined manner. One thing to note is that the notion of class and object in JavaScript is blurred and there is no real notion of class, so it is better thinking of one object sharing properties with other objects rather than one class extending another.

3.2.1. Class.create and the initialize method

Rather than taking the JavaScript approach of defining a constructor function and separately defining its methods, we can define a class in one go using:

Class.create.
var Point = Class.create();

This creates a class template that delegates to a method called initialize,, which can be considered from Prototype's point of view as its constructor.

We then define the prototype object for this class, defining its constructor (initialize) and methods in one go.

Point.prototype =
{
       initialize : function(x, y)
       {
              this.x = x;
              this.y = y;
       },
       toString : function()
       {
              return "Point(" +this.x+","+this.y+")";
       }
}

3.2.2. Extending classes

Like most OO langauges, Prototype allows us to create an object by extending an existing object, although the way it achieves this is quite different. Prototype uses the method Object.extend to implement extension.

This method takes two objects—a source and a destination—and copies each of the properties from the source to the destination before returning the destination. This ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required