I'm trying to understand jQuery, but I'm hindered by the syntax looking so strange to me. I don't even understand how a regular JavaScript parser parses it! I can read sample code and I'll understand from the accompanying material what it's doing, but I don't understand how.
I understand that $ is just an alias for jQuery, but that doesn't answer the question. Take the classic jQuery function used to delay things until the page is fully loaded:
$(document).ready(function() {
...
});
or a jQuery selector that selects all p elements in the DOM and applies a CSS rule:
$('p').css('color', 'blue');
So... somehow document and 'p' are recognized as keys, and associated with the appropriate values, right? Except that doesn't seem like it could be true, because then jQuery would have to pre-calculate the results it was going to return for any possible key it could be asked for, including element ids that jQuery probably couldn't know about! So how on earth does it really work?
(edited to fix an error in describing code)
The answer is simpler than you think. The $ is indeed an alias for the jQuery library... which is implemented as a single function. When you see code that looks like this:
$(document).ready(function() {
...
});
What you are seeing is:
$) being called...document ...ready method, that gets called ...I had trouble with this when I first ran into it. I knew that in JavaScript, functions are first-class objects (which is why you can pass one as an argument) but somehow, that didn't make clear to me that something which was clearly a large, sophisticated object (i.e., the jQuery library) might also be a function.
In fact, it's both. It's a function, and it's also an object that has its own properties, which include functions. That's why sometimes you'll see code like the following:
$.getJSON('http://www.foo.com/search?q=....
In our previous code, $ was the function we were calling. In this code, $ is the object on which the function we are calling, getJSON, is located.
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