I’m quite experienced with jQuery but I’m just getting into object oriented Javascript and want to make sure I’m doing it right.
Here’s an example of what I’m doing so far… I’d appreciate tips/advice on how I can improve my approach:
// create a class for collapsable fieldsets
window.CollapsableFieldset = (function() {
function CollapsableFieldset(jQObject) {
// look for all the legend tags within this fieldset
jQObject.find("legend").click(function(event) {
// add or remove the "open" class to the fieldset
return jQObject.toggleClass("open");
});
}
return CollapsableFieldset;
})();
jQuery(document).ready(function() {
return $("fieldset.collapsable").each(function(i, element) {
return new CollapsableFieldset($(element));
});
});
So basically I’m creating a class that defines the behaviour I’m looking for and then in the jQuery block, I’m selecting each object that matches and creating a new instance of the class with that object as an argument.
This is not object-oriented javascript.
Before getting into prototyping, let me make one remark: your use of a closure in CollapsableFieldset is unnecessary and cumbersome. Indeed, you do not have any variables in the (function(){})() pattern. You may rewrite, without any loss, to:
Now, you create classes in javascript using a function constructor, in which the “this” keyword defines the object that a “new” statement will yield:
Please bear in mind that object-oriented javascript is not always the optimal solution.