I use the jQuery extend function to extend a class prototype.
For example:
MyWidget = function(name_var) {   this.init(name_var); }  $.extend(MyWidget.prototype, {    // object variables    widget_name: '',     init: function(widget_name) {      // do initialization here      this.widget_name = widget_name;    },     doSomething: function() {      // an example object method      alert('my name is '+this.widget_name);    } });   // example of using the class built above var widget1 = new MyWidget('widget one'); widget1.doSomething();   Is there a better way to do this? Is there a cleaner way to create the class above with only one statement instead of two?
jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.
jQuery – create object oriented classes in jQueryCreate an object oriented style with jQuery. Make use of the constructor() method and access public and private methods from within the class scope.
A jQuery object is array-like which means that it contains zero or more indexes (properties which names are positive integers starting with zero). Besides those indexes, a jQuery object contains these properties: length. context. selector.
I quite like John Resig's Simple JavaScript Inheritance.
var MyWidget = Class.extend({   init: function(widget_name){     this.widget_name = widget_name;   },    doSomething: function() {     alert('my name is ' + this.widget_name);   } });   NB: The "Class" object demonstrated above isn't included in jQuery itself - it's a 25 line snippet from Mr. jQuery himself, provided in the article above.
Why not just use the simple OOP that JavaScript itself provides...long before jQuery?
var myClass = function(){}; myClass.prototype = {     some_property: null,     some_other_property: 0,      doSomething: function(msg) {         this.some_property = msg;         alert(this.some_property);     } };   Then you just create an instance of the class:
var myClassObject = new myClass(); myClassObject.doSomething("Hello Worlds");   Simple!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With