I need to build a small JavaScript library that would only be a couple kilobytes in size. To that end I would like to use some of the design choices that jQuery has made so famous.
Below are the two shells I have so far, and I was wondering if someone could advise me as to which style would probably be a better design choice.
var jQuery, $;
(function() {
jQuery = $ = function(selector, context)
{
return new JQuery(selector, context);
};
var JQuery = function(selector, context)
{
// ...
return this;
};
jQuery.fn = JQuery.prototype = {
example: function()
{
//...
return this;
}
};
}());
There is also a slightly modified version of the jQuery shell.
(function(window, undefined)
{
var jQuery = function(selector, context)
{
return new jQuery.fn.init(selector, context);
};
jQuery.fn = jQuery.prototype = {
init: function(selector, context)
{
// ...
return this;
},
example: function()
{
//...
return this;
}
}
jQuery.fn.init.prototype = jQuery.fn;
window.jQuery = window.$ = jQuery;
})(window);
I would also like to know if I’m making any bad design choices with either of these. JavaScript is not my primary language so I would like to make sure I’m not doing anything incorrectly.
jQueryfor a library, which is not, in fact, jQuery, is a pretty bad design choice in the first place.windowprefix for the global variables, which is bad for readability and strict mode compliancejQuery.prototypein the second example seems pointlessfnand thus accessible from outside