在阅读下面的性能测试时,我注意到作者使用了$(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");
}
}发布于 2012-03-18 10:32:54
如果查看jQuery source code,可以看到在执行$()时调用了init。此函数包含几个if语句,用于处理作为选择器传递的各种信息。在函数的末尾,将调用以下代码:
return jQuery.makeArray( selector, this );如果传递了一个数字,比如1或2,对makeArray的调用只会把它转换成一个数组,比如[1],[2]等等。所以$(1)没有什么特别之处。
https://stackoverflow.com/questions/9755455
复制相似问题