小型的jQuery式库设计?

时间:2011-11-05 16:14:57

标签: jquery javascript

我需要构建一个只有几千字节的小型JavaScript库。为此,我想使用jQuery如此着名的一些设计选择。

下面是我到目前为止的两个炮弹,我想知道是否有人可以告诉我哪种风格可能是更好的设计选择。

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;
        }
    };

}());

还有一个稍微修改过的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);

我还想知道我是否正在使用其中任何一种做出任何糟糕的设计选择。 JavaScript不是我的主要语言,因此我想确保我没有做错任何事情。

1 个答案:

答案 0 :(得分:3)

  • 使用名称jQuery作为库,实际上不是jQuery,首先是一个非常糟糕的设计选择。
  • 第一个示例没有全局变量的window前缀,这对可读性和严格模式合规性不利
  • 在第二个示例中设置jQuery.prototype似乎毫无意义
  • 我更喜欢构造函数是fn成员的版本,因此可以从外部访问