Wednesday, July 25, 2007

Prototype Javascript Framework - Creating classes

Here it is a quick review of how you can implement classes in Javascript using the Prototype Framework. (This was taken of the Prototype reference document that you can find in http://beta.bigmedium.com/projects/prototype-pdf/index.shtml)

If you are familiar with Object Oriented Programming, handling classes in Javascript would be really easy and Prototype makes easier.

Another advantage of using classes in Javascript is that you can have cleaner code, easy to use and maintain.

I'll show you now how to create a class using Prototype.

create() -> Function

Returns an function that acts like a Ruby class.

Class.create() returns a function that, when called, will fire its own initialize method.It also lets you more easily subclass by overriding a parent's constructor.

Example:

var Person = Class.create();
Person.prototype = {
    initialize: function(name, lastname, age) {
         this.name = name;
         this.lastname = lastname;
         this.age = age;
     },
     myAge: function() {
         alert("My age is " + this.age);
    }
};

var john = new Person("John", "Doe", 25);
john.myAge();
// -> alerts "My age is 25"

var Employee = Class.create();
Employee.prototype = Object.extend(new Person(), {
     initialize: function(name, lastname, age, job) {
         this.name = name;
         this.lastname= "lastname";
         this.age = age;
         this.job = job;
     },

     myJob: function() {
         alert("I work as a " + this.job);
    }
});

var susan = new Employee("Susan", "Smith", 30, "Teacher");
susan.myJob();
// -> alerts "I work as a Teacher"