
JQuery – Create object oriented classes
If you want to use an object oriented develompent schema in your jquery implementation, the following lecagy class would be useful for you.
Basically, we will need to define a constructor, with all its public methods, private methods and attributes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
/* * myClass */ var myClass = function(options){ /* * Variables accessible * in the class */ var vars = { myVar : 'original Value' }; /* * Can access this.method * inside other methods using * root.method() */ var root = this; /* * Constructor */ this.construct = function(options){ $.extend(vars , options); }; /* * Public method * Can be called outside class */ this.myPublicMethod = function(){ console.log(vars.myVar); myPrivateMethod(); }; /* * Private method * Can only be called inside class */ var myPrivateMethod = function() { console.log('accessed private method'); }; /* * Pass options when class instantiated */ this.construct(options); }; /* * USAGE */ /* * Set variable myVar to new value */ var newMyClass = new myClass({ myVar : 'new Value' }); /* * Call myMethod inside myClass */ newMyClass.myPublicMethod(); |
Thanks joebuckle