I’ve written my first jQuery plugin and it goes a little something like this.
(function ($) {
$.fn.MyFancyPlugin= function (settings) {
var defaults = {
someSetting = 'default for some setting'
};
var settings = $.extend({}, defaults, settings);
function foo(){
// do stuff
};
function bar(){
// do stuff
};
return this.each(function (){
// do more stuff
});
};
})(jQuery);
The plugin works just fine, but I’m so freaking anal about the looks that I hate the way the functions are nested.
My “preference” for the look of my JS is something like this.
MyNamespace.Class1 = {
foo: 'foo',
bar: function() {
return 'bar';
}
};
But I can’t seem to wrap my head around this when making a jQuery plugin. Can someone lend a hand? I’m most concerned about the var‘s and the fact that they’re private.
On a side note, I’d like to know what the “official” names are for each of these approaches to structuring JavaScript.
There’s nothing at all wrong with your first example, which is loosely the “module” pattern, except it may be duplicating the functions unnecessarily. Your latter example is just how you assign anonymous functions to properties on an object, which is inappropriate if the functions in question don’t need to be properties of the object.
Limiting the scope of functions by wrapping them in other functions is a fundamental JavaScript idiom, not ugly at all.
However, if
fooandbardon’t need access to the variables and arguments in scope when your plug-in function is called (and ifdefaultsis really static), you can move them out a level so they’re not recreated every time your plug-in is called:Also note that I corrected the syntax of your
defaultsinitializer (:, not=).Side note: Since your plug-in function isn’t a constructor function, the overwhelming convention in the JavaScript world is to use camelCasing with an initial lower case letter (e.g.,
myFancyPluginrather thanMyFancyPlugin).