在阅读以下性能测试时,我注意到作者使用过$(0)和$(1).这样做的目的是什么?
http://jsperf.com/scriptjunkie-premature-3
var $a = $(0);
function fn_1() {
var $a = $(this);
if ($a.attr("rel") == "foo") {
$a.addClass("foo");
}
else {
$a.addClass("other");
}
}
function fn_2() {
$a.context = $a[0] = this; // fake the collection object
if ($a.attr("rel") == "foo") {
$a.addClass("foo");
}
else {
$a.addClass("other");
}
}
Run Code Online (Sandbox Code Playgroud)
如果您查看jQuery 源代码,您可以看到执行init时会调用它。$()该函数包含多个if语句来处理作为选择器传递的各种信息。在函数末尾调用以下内容:
return jQuery.makeArray( selector, this );
Run Code Online (Sandbox Code Playgroud)
1如果传递诸如或 之类的数字2,则调用makeArray只会将其转换为数组,例如[1],[2]等。因此 没有什么特别之处$(1)。