Recent Weblogs

Links I like

Javascript Class

Function is the base object that so much of the language relies on. It allows scope, inheritance, composition and many other patterns of programming that allows developers to create the systems that they do. Prototype.js has enhanced this object to allow for ease of use when creating these systems. In particular the assets that assist this process is, Class.create, Function.prototype.bind and Object.extend


Class.create returns a function that executes the initialize function that all classes must inherit at some point before becoming instantiable. What this does is everytime you create a new instantation of your class it returns a function prebound to that instance and executes the initialize function for you. This is very similar to having a constructor function that executes everytime you create a new instance of the class.


Object.extend is a function that allows easy implementation of composition. It accepts two variables, the destination being the first, which is the variable that you want to inherit properties, and the source which is the variable that you want to propogate its properties into the destination.


Function.prototype.bind extends the native functionality of all functions created. Bind is a property of all functions that returns a function that is prebound(using the apply property) to the variable sent to the first parameter of bind. This functionality reveals its potential in many circumstances, I have found it useful when attaching event listeners and when iterating through collections.

View Code

So lets take a look at a little example of an implementation of a javascript class

var Super = Class.create();
var Sub = Class.create();

                        name : "Super",
                        initialize : function(param){
                        inheritance : function(){
                            alert("I have inherited this function  -- All ye mighty, look upon my works and despair."  +;
Object.extend(Object.extend(Sub.prototype, Super.prototype),
                    name : "Sub",
                    initialize : function(obj){
                        this.obj = $(obj);                            
                        Event.observe(this.obj, "click", this.inheritance.bindAsEventListener(this));                                    
For an example of this at work click the button -->

Comments are Disabled.