Why is jQuery's syntax so weird - how does it even parse?

I'm trying to understand jQuery, but I'm getting in the way of the syntax looking so strange to me. I don't even understand how the regular JavaScript parser parses it! I can read the example code and I can understand from the accompanying material what it does, but I don't understand how .

I realize that it $

is just an alias for jQuery, but that doesn't answer the question. Take the classic jQuery function used to delay until the page is fully loaded:

$(document).ready(function() {
  ...
});

      

or a jQuery selector that selects all elements p

in the DOM and applies a CSS rule:

$('p').css('color', 'blue');

      

So ... somehow document

both are 'p'

recognized as keys and are associated with the corresponding values, right? Except that it doesn't seem like it might be true because then jQuery had to pre-compute the results it was going to return for any possible key that could be given for, including element ids, which jQuery is likely to , could not know! So how does it actually work?

(edited to correct an error in the code description)

+3


source to share


1 answer


The answer is simpler than you think. $

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 do you see:

  • The jQuery ( $

    ) function is called ...
  • ... with an argument document

    ...
  • ... which returns an object ...
  • ... which has a method ready

    that gets called ...
  • ... with an anonymous function for its argument.


I had problems with this when I first encountered this. I knew that in JavaScript, functions are first-class objects (so you can pass them as an argument), but somehow it doesn't make it clear to me that something is clearly a large complex object (i.e. a jQuery library) could also be function.

In fact, this is both. It is a function, and also an object that has its own properties that include functions. Therefore, sometimes you will see code similar to the following:

$.getJSON('http://www.foo.com/search?q=....

      

Our previous code $

had a function that we were calling. This code $

contains the object on which the function we are calling is called getJSON

.

+9


source







All Articles