For jQuery plugin why add object definition to $ instead of globaly?
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 glo开发者_运维百科baly?
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.js
is being added to the page, you can expect it to add
window.foo = {};
//or
window.foo = function(){};
It would be silly of any developer to use two scripts /path/to/foo.js
and /different/path/to/foo.js
and 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 jQuery
object 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.js
and /different/path/to/jQuery.foo.js
and 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.foo
might also want $.foo.defaultSettings
to be persistent and extensible.
As far as advantages go, adding jQuery plugins to the jQuery
object reduces global pollution, and I don't know anyone who likes pollution.
Many javascript libraries such as jquery try not to "pollute" the global namespace. The reason is that if multiple libraries, or a library and the web page itself, use the same global variable name then one might break the other. For something as widely adopted as jquery, this would be very likely to cause a conflict. Even for a plugin it would be a bad practice.
Actually, the same issue could occur inside the jquery object itself, so the plugin really shouldn't even set $.MyObj, (what if another plugin did the same?), but I suppose the author thought it was less bad.
精彩评论