Xeoncross
Xeoncross

Reputation: 57184

Small, jQuery-like library design?

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.

Upvotes: 3

Views: 933

Answers (1)

Tgr
Tgr

Reputation: 28160

  • using the name jQuery for a library, which is not, in fact, jQuery, is a pretty bad design choice in the first place.
  • the first example has no window prefix for the global variables, which is bad for readability and strict mode compliance
  • setting jQuery.prototype in the second example seems pointless
  • I would prefer the version where the constructor is a member of fn and thus accessible from outside

Upvotes: 3

Related Questions