Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to create an object-oriented class with jQuery?

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?

like image 439
Devon Avatar asked Sep 17 '08 15:09

Devon


People also ask

Is jQuery an OOP?

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.

Can we create class in jQuery?

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.

What is jQuery object?

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.


2 Answers

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.

like image 172
Jonny Buchanan Avatar answered Sep 19 '22 19:09

Jonny Buchanan


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!

like image 21
Paul Allsopp Avatar answered Sep 21 '22 19:09

Paul Allsopp