OB电竞在线
$
, and that encourages the use of
shorthand objects
,
anonymous functions
and
method chaining
. jQuery is not alone — libraries like
YUI
(Yahoo User Interface) do similar things.
Have you ever come across a bit of JavaScript like
$(".cta").click(function(){})
and thought, “What the $(‘#x’) is that” If it looks like gibberish to you, then please read on. If you think that snippet of code couldn’t possibly be real, then please browse some
jQuery examples
. They are full of such constructions.
This article covers the key concepts that underly such intimidating fragments of code, but we’ll start with a longer example, based on a simple example of animating a square. You are probably not required to do this every day, but it makes for a concise and tidy demonstration:
$(document).ready(function(){ $("button").click(function(){ $("div").animate({height:"toggle"}).append("hi"); }); });
We’ll go through every word and feature of the code above, along with a detailed look at JavaScript functions, the jQuery object and event-driven programming . By the end, you will hopefully no longer feel anxious in the face of such inscrutable code.
What Is
$
?
At first glance,
$
looks like some special, complex JavaScript functionality. It’s not. The dollar symbol has no special significance in JavaScript. In fact,
$
is just a function. It is an alternative name for the
jQuery
function
.
And the
jQuery
function is the raison d’être of the very popular
jQuery library
. jQuery is a compact JavaScript library that irons out many of the annoying differences between browser manufacturers and provides many useful features for manipulating and animating parts of Web pages. You can include the
jQuery
function (i.e.
$
) in your page by referencing a copy of the library:
Alternatively, you can download your own copy from jQuery’s website :

The
jQuery
function usually takes a single argument, either a
selector
or a JavaScript reference to something on the page, such as
document
.
A selector is just a piece of CSS, the part before the
At the beginning of our example,
Remember that
The
In this example, the variable
You can also assign functions as properties of an object. Gerbils are generally very quiet rodents, but occasionally they make a high-pitched meeping sort of noise. In JavaScript, that might look like this:
In JavaScript, the boundaries between variables, functions and objects are quite blurred. So, a function can easily be assigned to a (member) variable:
You can now call this function to make the gerbil speak:
In object-oriented parlance, this is now a
member function
, or a
method
. Methods may refer to other methods and member variables within the same object. Imagine that Digger has learned to speak English, which is quite remarkable for a gerbil:
In the
Objects can also be used as the return values for functions. This is a nice function that I use all of the time:
This will return a reference to the (global) variable or object
However, you can skip the intermediary variable and just call
Stripped of the inner code, this is the same programmatic structure as in the first line of our original example:
The next section describes what
The shorthand object notation looks like
The keyword
In JavaScript, there are several ways to create functions. The following is the classic way (a
function declaration
), which should be familiar to anyone who has done some programming:
We’ve seen above that functions can be assigned to variables. We created the
In JavaScript, functions may be assigned to variables and passed around just like any other variable. Consider this rather useless function:
It has one argument, called
This would simply run the
In fact, anywhere
Instead of that, you could put an anonymous function in place of
This technique is often used to provide variable scoping in JavaScript. Can you follow what this code will do?
The
Because our gerbil is no longer doing any high-pitched squeaking, the code above uses
Anonymous functions are the next piece of the puzzle. jQuery’s
The
Anonymous functions are functions without a name, like
Before delving further into the sample code, we need to review one more concept that often occurs in JavaScript.
Method chaining
refers to running several functions in a row. This is really just an extension of the
Let’s redefine the gerbil-related functions to return a reference to themselves.
These two functions now do something to
This line of code will first run
Next, the
After that,
This sort of chaining often happens in JavaScript. You might see it with
The code above starts with the full string
Of course, chaining happens all over the place in jQuery and appears in our example:
The
These chains can get long. Below is a
particularly long jQuery chain
, proudly posted several years ago:
Generally speaking, long chains like this are hard to debug and maintain. So, avoiding really long ones is usually a good idea, but they can be useful in miniature.
Functions belonging to objects (i.e. methods) that return references to themselves may be chained together, allowing you to execute a lot of code without storing the intermediate results.
Our example uses several jQuery methods:
These functions are all methods of the jQuery object, and they all return a jQuery object. Internally, though, the jQuery object is far more sophisticated than
As mentioned earlier, the barriers between concepts can get blurry in JavaScript. The jQuery object behaves like an object and an array. You treat it like an object when you chain, but you can also treat it like an array:
In this example,
Achieving the same result by turning these nodes back into jQuery objects and then calling the jQuery method
Both of these will output the HTML contents of each
Note that when you run a piece of jQuery such as
The jQuery function
We can now look at the example as a whole. The
This function uses the main
This function looks up all
The
Every time the
This snippet looks innocent enough:
You would expect the
To be fair, this issue is not caused by jQuery or by anonymous functions, but it is a hazard of event-driven programming in general. The lines above run at three different times: when they are first processed (
Server-side code written in languages such as PHP runs sequentially and in order, from beginning to end, outputting HTML to make a Web page and then finishing. JavaScript can do this, too, but it is most powerful when attached to events, such as button clicks. This is
event-driven programming
, and it’s not only JavaScript. The programming behind smartphone apps is also largely event-driven, with Objective-C or Java or C++ responding to touchscreen events on your Apple, Android or Windows phone.
If the code above were translated into Java and run on an Android phone, then the reference to
One quick way to avoid headaches like this is to scope your variables. This example can be fixed by declaring the variable
If you must use a global configuration variable, then another technique is to name and group the variables well. And clearly commenting your code is always recommended:
{…}
. So,
$("div")
is the same as
jQuery("div")
and behaves very roughly like the following CSS by selecting all of the
$(document)
passes the JavaScript variable
document
into the
jQuery
function. The
document
variable is set automatically by the browser. It refers to the top of the
document object model
(DOM). The DOM is the browser’s own analysis of all of the HTML in the page, upon which the functionality of jQuery is built. For example, jQuery’s
$("div")
does roughly the same thing as
document.getElementsByTagName("div")
.
Key Takeaway
$
is just a function, an alternative and handier name for the
jQuery
function.
The Dot
.
that comes after
$(document)
signifies a wealth of functionality. The dot is used with JavaScript objects. At its simplest, a JavaScript object is a collection of properties. For example:
var digger = new Object(); digger.species = "gerbil"; digger.name = "Digger"; digger.color = "white";
digger
is an object, and we have assigned it three subvariables:
species
,
name
and
color
. In object-oriented jargon, these are known as
member variables
. All of the above can be written more concisely as this:
var digger = {species:"gerbil", name:"Digger", color:"white"};
function meepMeep(){ alert("meep meep"); }
digger.speak = meepMeep;
digger.speak();
function myNameIs(){ alert("Meep! I am a " + this.species); } //assign the function digger.sayMyName = myNameIs; //call the function digger.sayMyName();
myNameIs
function, the special variable
this
refers to the containing object, and
this.species
is the same as
digger.species
and has the value
gerbil
. If you tried to call
myNameIs()
by itself, without the object, then
this
would refer to the JavaScript
window
object and
this.species
would be
window.species
, which is undefined. The page would alert “Meep! I am a undefined.”
function giveMeTheGerbil(){ return digger; }
digger
, which you can then treat in exactly the same way as the original
digger
:
var digger2 = giveMeTheGerbil(); //alerts "Meep! I am a gerbil" digger2.sayMyName();
sayMyName
directly on the returned value of
giveMeTheGerbil
:
giveMeTheGerbil().sayMyName();
$(document).ready(…);
ready
actually does.
Key Points
{name:"Digger", species:"gerbil"}
.
this
is used in a function attached to an object (a method) and refers to the containing object.
Anonymous Functions
function meepMeep(){ alert("meep meep"); }
meepMeep
function and assigned it to
digger.speak
. In fact, functions may be created anonymously (called a function expression), without any name at all, and then assigned to a variable:
var meepMeep = function(){ alert("meep meep"); };
function runMe(f){ f(); }
f
.
runMe
treats that argument like a function and runs it. So, you could call this:
runMe(meepMeep);
meepMeep
function. It gets more interesting when you don’t even bother to officially name
meepMeep
at all. You could simply create it when needed and pass it immediately into
runMe
:
runMe(function(){ alert("meep meep"); });
meepMeep
can appear, so can its anonymous equivalent. Take this:
meepMeep();
meepMeep
, although wrapping it in an extra set of parentheses is required:
(function(){ alert("meep meep"); })();
var x=3; (function(){ var x=4; console.log("x is " + x); })(); console.log ("x is " + x);
var
keyword within the function is important here. It declares a variable within a function. The anonymous function here defines its own local variable,
x
, assigns it the value
4
and then outputs it. Because of the
var
keyword, the function’s
x
remains completely separate from the
var x=3
on the previous line. Therefore, this code will output
x is 4
and then
x is 3
.
console.log
, rather than
alert
, to output its result. The
console.log
is available in modern browsers (in other words, not in old Internet Explorers) and shows its output unobtrusively in the browser’s
error, Web or JavaScript console
.
ready
method is like a time-delayed version of the
runMe
function above. The
ready
method waits until the DOM has fully loaded and then runs the provided function. So, when the
document
is finally
ready
, the following anonymous function will run:
function(){ $("button").click (…) }
$(document).ready(…)
is a common way for programmers to execute some JavaScript only after all of the HTML document has been processed.
Key Takeaway
function(){alert(1);}
. They can be assigned to variables, passed into other functions or run immediately to provide scoping.
Method Chaining
giveMeTheGerbil()
example above:
giveMeTheGerbil().sayMyName();
digger.speak = function(){ alert("meep meep"); return this; } digger.sayMyName = function(){ alert("Meep! I am a " + this.species); return this; }
digger
and then return
digger
. Not much different, but the addition allows us to chain the functions together:
giveMeTheGerbil().speak().sayMyName().speak();
giveMeTheGerbil
, returning a reference to the
digger
object. Now, it essentially becomes equivalent to this:
digger.speak().sayMyName().speak();
speak
method of the
digger
object runs and alerts
meep meep
. This also returns a reference to
digger
, and then the code becomes this:
digger.sayMyName().speak();
sayMyName
runs and again returns a reference to
digger
, etc. It will cause three alerts:
meep meep
,
Meep! I am a gerbil
,
meep meep
.
string
objects:
var s = "I have a dagger."; console.log(s.substring(9, 15).replace("a", "i").toUpperCase());
s
, extracts a substring, replaces the letter “a” with “i,” changes the resulting word to uppercase and returns the resulting string, which is shown in the console log.
$("div").animate({height:"toggle"}).append("hi");
$("div")
looks up all
animate
method on the jQuery object and then runs
append
, each time returning and operating on a jQuery object.
A very long jQuery chain.
Key Takeaway
The jQuery Object
ready
,
click
,
animate
and
append
. These are all functions attached to the jQuery object, similar to how
speak
and
myNameIs
are functions attached to the
digger
object and to how
substr
,
replace
and
toUpperCase
go with strings.
digger
or a
string
could ever hope to be.
var mydivs = $("div"); for (var i = 0; i < mydivs.length; i++) {console.log(mydivs[i].innerHTML);}
$("div")
looks up all
mydivs
variable. The code loops through the jQuery object as if it were an array of nodes (actually, a
NodeList
) in the DOM. These nodes are also
objects
with properties of their own, such as
outerHTML
and
innerHTML
.
html
is also possible. To do this, pass them into
$
, which turns pretty much anything into a jQuery object:
var mydivs = $("div"); for (var i = 0; i < mydivs.length; i++) {console.log($(mydivs[i]).html());}
$("div").animate(…).append(…);
, the animation happens on all of the
Key Takeaway
$
and many of the jQuery methods like
click
and
animate
return a jQuery object, which is part object and part array. The array-like part contains references to nodes in the DOM.
Putting It All Together
$(document)
returns a jQuery object referring to the page itself. The
.ready(…)
is passed a function that runs when the page has finished parsing and the DOM is fully available:
function(){ $("button").click(…); }
jQuery
function to look up all
elements in the page. It returns a jQuery object that has a
click
method. The
click
method is passed another anonymous function:
function(){ $("div").animate ({height:"toggle"}).append("hi"); }
animate
method. The argument to jQuery’s
animate
method is a list of properties to animate, passed in as the shorthand object
{height:"toggle"}
. This tells jQuery to toggle the height of all
animate
method also returns a jQuery object. This is chained to the
append
method that adds the “hi” string to every
is clicked, the green
Event-Driven Headaches
//set h to 200 var h = 200; $(document).ready(function(){ $("button").click(function(){ //animate up to h, 200 pixels high $("div").animate({height:h}); }); });
h
being assigned the value of
200
and the animation actually running. In a complex jQuery application, the variable name
h
might get reused, or some other part of your application might change the value. And you will stare intently at those few lines of code wondering why on Earth your box animates to only 50 pixels high, instead of 200. It’s because somewhere else in your code, you might have an unobtrusive
for (h=1; h
<50; h++) {…}
changing the value of
h
.
$(document).ready(…)
), when the document loads (
$("button").click(…)
) and when the button is clicked (
$("div").animate(…)
).
h
in the innermost function would cause an error. This is because
h
has not been declared as a global (or
static
in Java) variable, and so the inner code has no idea what its value should be. While that wouldn’t change the issue, it would at least force you to think more clearly about how to use variables.
var h
in the first anonymous function. Now, that
h
will take precedence over any other global
h
:
$(document).ready (function(){ //set h to 200 var h = 200; $("button").click (function(){ //animate up to h, 200 pixels high $("div").animate ({height:h}); }); });
//properties of the animation var animationConfig = {upToHeight:200}; //when document is loaded $(document).ready(function(){ //when any