gpt4 book ai didi

jquery - 小型的、类似 jQuery 的库设计?

转载 作者:行者123 更新时间:2023-11-29 10:52:14 26 4
gpt4 key购买 nike

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

以下是我目前拥有的两个 shell,我想知道是否有人可以建议我哪种样式可能是更好的设计选择。

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 不是我的主要语言,所以我想确保我没有做错任何事情。

最佳答案

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

关于jquery - 小型的、类似 jQuery 的库设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8021429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com