Jquery - Object Oriented Programming
Jquery - Object Oriented Programming
OOPS here , OOPS there and OOPS everywhere. Does jQuery support object oriented programming?
I put a * next to YES. Did you see that. It means Conditions Apply. We will talk about the conditions apply later.
Class Declaration
var simpleClass = { };
Thats it?. A ributes? Methods ?. Where are they?. Lets see how can we fit those in inside this empty class.
};
Perfect!!!!.
Conditions Apply
Private Variable
There aint any private variables here. To access the testA ribute, just use
simpleClassObj.testAttriute;
Enough!!
simpleClassObj.testAttribute2 = 'test2';
Do you think, it will work. compilation error??. Duh!. It will still work. Our exceptional system will modify the source class for us ( Amazing huh!!).
You can clearly see, jQuery has sold the encapsulation feature for duck typing. Only god knows, the actual state of an object here.
Now, the question. If not for encapsulation, why do we need to go for OOPS approach in jQuery. The answer is Organization.
Can you see, these three simple statements have absolutely no similarity (except the object part). Imagine a similar style of code , in a page which
has plenty of dom objects and widgets. Do you think its easy to understand??.
Lets create a simple abstract class ( Dont search for the abstract keyword. We dont have one. if you want an abstract class, be er YOU dont
instantiate it)
var syndrome = {
doHide : function(){
this.hide('slow');
},
doShow : function(){
this.show( 'slow' );
},
doDisable : function(){
this.attr('disabled', 'disabled');
},
toggle : function(){
this.toggle();
},
getStyle : function(){
return this.attr('style');
},
setForeground : function(color){
var style = 'color:'+color+';';
this.attr('style', style+this.getStyle());
},
setBackground : function(color){
var style = 'background-color:'+color+';';
this.attr('style', style+this.getStyle());
},
getName : function(){
return this.attr('name');
},
getValue : function(){
return this.attr('value');
},
getClass : function() {
return this.attr('class');
},
getContent : function(){
return this.html();
}
};
Its easily readable, you can see what am doing. Just put some common methods. Now , lets see how can we use this in our above example.
$.Extend( testObj, syndrome ); //extending the abstract class. So , the method should be available here.
testObjtestObj.getValue(); // Get value
testObj.getName(); // Get Name
testObj.getContent(); // Get content
Now this looks neat and clean. Now Imagine the same scenario, a lot of components and widgets. What will you have . Just a list of $.Extend
statements with pure object interaction.