I\'m working on a project and I\'m really trying to write object-oriented JavaScript code. I have just started reading Douglas Crockford\'s JavaScript: The Good Parts and I\'m q
I would say the first way you're creating methods is a misuse of jQuery. The jQuery.fn.foo
syntax is generally reserved for functions that act upon a DOM element but you're using them as static functions, by using an empty jQuery object.
If you want to create static functions under the jQuery namespace, you can do:
jQuery.foo = function(){};
then call it via:
jQuery.foo();
instead of:
jQuery.fn.foo = function(){};
which allows you to do:
jQuery('#someElementId').foo();
In terms of OOP. there are many different approaches (module pattern, prototype, factory...). The way I generally approach it, is create a Class as a static function, then invoking it with the keyword new
(function($){
var undefined;
$.ClassName = function(options){
var self = this;
var cfg = $.extend(true, {}, this.defaults, options);
// ********************
// start:private
// ********************
function _init(){
};
// ********************
// start:public
// ********************
this.methodName = function(){
};
_init();
};
$.ClassName.prototype.defaults = {};
})(jQuery);
In terms of reusing functionality, there's a threshold after which decoupling is more detrimental than anything. Make sure you keep the right balance of modularity and organization.