Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is jQuery syntax so strange - how does it even get parsed? [duplicate]

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)

like image 473
afeldspar Avatar asked Oct 27 '25 06:10

afeldspar


1 Answers

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:

  1. The jQuery function ($) being called...
  2. ... with the argument document ...
  3. ... which returns an object ...
  4. ... which has a ready method, that gets called ...
  5. ... with an anonymous function for its argument.

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.

like image 132
afeldspar Avatar answered Oct 29 '25 19:10

afeldspar