我需要构建一个只有几千字节的小型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不是我的主要语言,因此我想确保我没有做错任何事情。
答案 0 :(得分:3)
jQuery
作为库,实际上不是jQuery,首先是一个非常糟糕的设计选择。window
前缀,这对可读性和严格模式合规性不利jQuery.prototype
似乎毫无意义fn
成员的版本,因此可以从外部访问