How can I get class-based objects in JavaScript with jQuery?
class, javascript, jquery
Solution
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();
Note: I asked a related question about this same topic.
Problem
I'm trying to move from Prototype to jQuery and there's one last thing I can't figure out how to do in the new library. Here's what I used to do with Prototype: ``` MyClass = Class.create(); MyClass.prototype = { initialize: function(options) { } } ``` Then I could create a new `MyClass` with: ``` var mc = new MyClass({}); ``` Does jQuery have anything like Prototype's `Class.create()`? And if not, how do I get the same kind of thing without a library?