Thursday, March 15, 2012

Inheritance in Javascript using jQuery

Here is a small JS code snippet, that allows you to create class trees with almost any inheritance complexity.
NB: Uses jQuery
createClass : function (a, b) {
    var c = function() {
        $(this.__constructor.apply(this,arguments));
    },e='prototype',f;
    if ($.isFunction(a)) {
        (f = function() { })[e] = a[e];
        ((c[e] = new f()).constructor = c).parentClass = a[e];
        a = b;
    }
    $.extend(c[e],a);
    return c;
}
Basic usage:
ClassA = createClass({
    __constructor : function() {
        
    }
});
ClassB = createClass(ClassA,{
    __constructor : function() {
        ClassB.parentClass.__constructor.apply(this,arguments);

    }
});
Inheritance power demonstration:
ClassA = createClass({
    __constructor : function() {
        
    },
    hello_world : function() {
        alert('ClassA says Hello World');
    }
});

ClassB = createClass(ClassA,{
    __constructor : function() {
        ClassB.parentClass.__constructor.apply(this,arguments);
        this.hello_world();
    },
    hello_world : function() {
        ClassB.parentClass.hello_world.apply(this,arguments);
        alert('ClassB says Hello World');
    }
});
This example will give you two alerts in the following order:
  • 1. 'ClassB says Hello World'
  • 2. 'ClassA says Hello World'
Important notes:
"__constructor" is just name, that can be replace with anything you'd like, I'm usually using "init"
"parentClass" also replaceable with any other keywords you'd like.


Happy using!

No comments:

Post a Comment