Pages

Search

Monday, March 5, 2012

Implementing Inheritance in JavaScript


Below example explains to build functions in a class and also implementing the inheritance.

if (typeof Test == 'undefined')
    Test = {};

Test.namespace = function (nmspace) {
    var nms = nmspace.split(".");
    var obj = Test;
    for (i = 0; i < nms.length; i++) {
        obj[nms[i]] = (obj[nms[i]]) ? obj[nms[i]] : {};
        obj = obj[nms[i]];
    }
}
Test.namespace("App.UI");

The above lines would help in creating namespaces and there after the functions are defined under specific namespace.

Test.App.UI.Base = function () {
    alert('parent class constructor');
}


Test.App.UI.Base.prototype.setInnerText = function (id, txt) {
    document.getElementById(id).innerText = txt;
}

Above functions are in class “Base” which falls in “Test.App.UI” namespace.


var objTest;

function LoadTest() {
    objTest = new Test.App.UI.Test();
}
Test.App.UI.Test = function () {
    Test.App.UI.Test.superclass.constructor.call(this, Test.App.UI.Base);
}

//calling below function will apply the iheritance
Test.extend(Test.App.UI.Test, Test.App.UI.Base);
Test.App.UI.Test.prototype.Hello = function () {
    alert(“hello”)
}

Test.App.UI.Test.prototype.SetValue = function (val) {
    objTest.setInnerText('lbl', resp.value);
}


Above functions are in“Test” class which also falls in “Test.App.UI” namespace.


Test.extend = function (subclass, superclass) {
    var fun = function () { };
    fun.prototype = superclass.prototype;
    subclass.prototype = new fun();
    subclass.prototype.constructor = subclass;
    subclass.superclass = superclass.prototype;
}


Test.extend function is used to apply the inheritance for the given two classes.

No comments:

Post a Comment