jQuery: class/klass pattern

The JavaScript klass() pattern is an utility function that mimics the basic behavior of those languages (such as PHP) that actually have an initialization method when creating classes. JavaScript is a class-free language, meaning that it's based on objects rather than classes. I found an interesting implementation of this pattern at http://code.google.com/p/jquery-klass/, but the source code wasn't available so I was stuck on it. A couple of months ago I read Stoyan Stefanov's JavaScript Pattern published by O'Reilly, one of the most interesting and inspiring books of ever. On Chapter 6, pages 128-30, Stoyan showed the way to implement this pattern. I decided to copy his code and adapt it to jQuery in the form of a global utility function, which is as follows:

/** jClass

   @author Gabriele Romanato
   @description jQuery implementation 
   of Stoyan Stefanov's klass() function
   @requires jQuery 1.4+
   @credits Idea: http://code.google.com/p/jquery-klass/
            Code: 'JavaScript Patterns' by Stoyan Stefanov 
            (O'Reilly) Chapter 6, pages 128-30 **/
            
            
            
(function($) {


  $.jClass = function(Parent, props) {
  
  
    var Child, F, i;
    
    Child = function() {
    
    
      if(Child.uber && Child.uber.hasOwnProperty('init')) {
      
        Child.uber.init.apply(this, arguments);
      
      
      }
      
      if(Child.prototype.hasOwnProperty('init')) {
      
      
        Child.prototype.init.apply(this, arguments);
      
      
      }
    
    
    
    
    };
    
    
    Parent = Parent || Object;
    
    F = function() {};
    
    F.prototype = Parent.prototype;
    
    Child.prototype = new F();
    
    Child.uber = Parent.prototype;
    
    Child.prototype.constructor = Child;
    
    for (i in props) {
    
      if(props.hasOwnProperty(i)) {
      
        Child.prototype[i] = props[i];
      
      
      }
    
    
    }
  
  
  return Child;
  
  };




})(jQuery)

I've only changed the name of the initialization method to init() and called this function jClass(). It basically handles object inheritance plus adding an initialization method that mimics the traditional way of handling classes used by classic OO languages. This pattern makes use of the uber construct popularized by Douglas Crockford to correctly handle the prototypal chain between the parent object and the returned child object. An example:

var Class = $.jClass(null, {
  init: function() {
    this.name = 'Test';
  },
  display: function() {
  
    alert(this.name);
  
  }
});

$(document).ready(function() {

  var myClass = new Class();
  myClass.display(); // alerts 'Test'

});

Example

Live example

Download

jquery.jclass.js

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.