I have been studying a jQuery plugin. The plugin extends $.fn as you would expect. However the plugin also defines an object for it’s use. The object is defined like so..
$.MyObj = function() {
}
$.MyObj.prototype.foo = "green";
Why would you make the object definition a property of $ ? Why not just define the object globaly?
MyObj = function() {
}
MyObj.prototype.foo = "green";
Are there any benefits to making the object definition a property of $ ?
General Plugin Convention
A good plugin designer will typically create a very small global footprint. If a reusable object or function is being provided, it needs to be accessible from somewhere.
Typically this is done by adding a single global object that contains the necessary functions (or is the necessary function).
Example: If a plugin
foo.jsis being added to the page, you can expect it to addIt would be silly of any developer to use two scripts
/path/to/foo.jsand/different/path/to/foo.jsand expect them to work nicely together, as they likely share the same namespace.With jQuery plugins, however, the plugins require jQuery. As such there is no reason to pollute the global namespace when you can guarantee that the
jQueryobject exists.As (by definition) jQuery plugins require jQuery, the suggested naming convention for a plugin is
jQuery.[plugin name].js. Just like normal plugins, it would be silly for a developer to use two scripts/path/to/jQuery.foo.jsand/different/path/to/jQuery.foo.jsand expect them to work nicely together.jQuery nuances
Some jQuery plugins extend
$.fn[pluginName], others are extra functions (like$.each,$.ajax, and$.extend), and a bunch extend jQuery’s selector capabilities. Each of them often require globally persistent data, be it default values, utility functions or what-have-you.A plugin that creates
$.fn.foomight also want$.foo.defaultSettingsto be persistent and extensible.As far as advantages go, adding jQuery plugins to the
jQueryobject reduces global pollution, and I don’t know anyone who likes pollution.