Create an object oriented style with jQuery. Make use of the constructor() method and access public and private methods from within the class scope.
/* * 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(); |
With thanks – https://www.scorchsoft.com/blog/how-to-write-object-oriented-javascript
Be First to Comment