Thursday, October 25, 2007

Javascript using Prototype.js framework

Prototype is a JavaScript Framework that aims to ease development of dynamic web applications. One of the objects they provided is the class object. Class is object for class-based OOP. (You can learn more about Prototype.js in Prototype.org )

In my last post, I explained the difference between javascript object and java object. Now, I will explain how to define a class with the use of Prototype.js.

To use Prototype, first you must include the framework. You can either download the prototype.js file or reference from it directly, like this:

<script type="text/javascript" src="http://www.prototypejs.org/assets/2007/6/20/prototype.js"></script>

Prototype’s Class object contains a single useful helper method which is create(), that allows us to move the body of the constructor into the prototype definition. (No need to specify the prototype directly, like what I did in prev post.)

The create() method does this for us by defining a constructor automatically that delegates to an initialize() method, which we then define manually.


var AnimalObj = Class.create();

AnimalObj.prototype = {

initialize:function() {
this.sound = "grr!";
},
playSound: function() {
alert(this.sound);
}
}


With prototype, you don't need a constructor (which in javascript a public global function ). You can define everything in the initialize method it provided.

Another cool feature about Prototype.js is the Object.extend() functionality. Object.extend() copies all properties from the source to the destination object. Used by Prototype to simulate inheritance (rather statically) by copying to prototypes.

The inheritance with Object.extend() works differently if you are used to java. For example, if we want to create Horse that extends Animal. It would be like this:

      
var Horse = Class.create();

Object.extend(Horse.prototype,AnimalObj.prototype);

Object.extend(Horse.prototype, {
initialize:function() {
this.sound = "neigh!!";
}
});


Looks weird huh? Well, first you create a class. Then you extend the methods in Animal to your Horse object. Then you define your initialization. Take note that you have to use Object.extend() in defining the initialize() method, otherwise it will override your previous object.

1 comment:

diobert said...

Thanks for sharing!



Practical Kanji