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?
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.
A JavaScript class is a type of function. Classes are declared with the class keyword. We will use function expression syntax to initialize a function and class expression syntax to initialize a class. We can access the [[Prototype]] of an object using the Object.
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
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.
jQuery uses the standard javascript functionality for creating new classes.
There are some fine examples on the web, but I would recommend looking at David Flanagan's books Javascript: The Definitive Guide.
Object-Oriented JavaScript
JavaScript and Object Oriented Programming (OOP)
I apologize, I completely misunderstood your original post. I'm guessing that you actually want to know how to extend the jQuery $ object. This is easily doable, there are a large number of plugins out there for doing so. There is a tutorial on the jQuery site for doing this: Getting Started With jQuery
Essentially, though, you use
jQuery.fn.foobar = function() {
// do something
};
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