Saturday, January 17, 2009

Using Ext.extend to extend user classes.

While learning javascript, I've fallen into the copy/paste trap of code creation. Rather than using OO constructs, I often copy a block of code, paste it and modify it slightly. This is bad bad bad so I thought I would figure out how to use Ext.Extend to take my own base class and use inheritance to extend the base functionality. There is no rocket science here but I can use this now as a template for inheriting. Code ...

// ----------- Base class (extending 'object' )  ------------------
genericBase = Ext.extend(Object, {
basevar1: 1,
constructor: function(args) {
this.basevar1 = 2;
},

baseFunc1: function(testArg) {
alert("test Arg is " + testArg + " basevar = " + this.basevar1);
}
});

// ----------- Derived class (extending 'genericBase'class ) -------
genericDerived = Ext.extend(genericBase, {
derVar: 444, // class property
constructor: function(args) {
// Call the base constructor
genericDerived.superclass.constructor.call(this, args);
},

derivedFunc1: function(testArg) {
alert("derivedFunc1 called " + testArg );
},
getBaseval: function() {
return this.basevar1;
}

});


// -------- Code to instantiate and test the classes

// First, create the object
var myobj = new genericDerived({prop1: '123', prop2: 'abc' });

// displays basevar with a get method
alert("Derived class, method call ==>" + myobj.getBaseval());

// also displays basevar, but with direct property reference
alert("explicit reference to property basevar1 ==> " + myobj.basevar1);

myobj.baseFunc1('Calling base method');
myobj.derivedFunc1('Calling derived class method');


No comments: