While reading the following performance test, I noticed the author used $(0)
and $(1)
. What is the purpose of this?
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");
}
}
In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.
It accesses the DOM element directly, without the jQuery wrapper.
$ is a short form of jQuery function. $() = jQuery() = window. $() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements.
The value of this inside a click event is a DOM element (the one that was clicked). Using $(this) converts it to a jQuery object. DOM elements do not have a hide() methods, but jQuery adds that and many other methods you can then call.
If you look at the jQuery source code, you can see that init
is called when $()
is executed. This function contains several if
statements to handle various pieces of information passed as the selector. At the end of the function the following is called:
return jQuery.makeArray( selector, this );
If a number such as 1
or 2
is passed, the call to makeArray
will just convert it to an array such as [1]
, [2]
, etc. So there is nothing particularly special about $(1)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With