Download ebooks file Learning JavaScript 2nd Edition Shelley Powers all chapters
Download ebooks file Learning JavaScript 2nd Edition Shelley Powers all chapters
com
https://ebookname.com/product/learning-javascript-2nd-
edition-shelley-powers/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/learning-node-1st-edition-shelley-
powers/
ebookname.com
https://ebookname.com/product/learning-javascript-design-patterns-a-
javascript-and-react-developer-s-guide-2nd-edition-adnan-osmani/
ebookname.com
https://ebookname.com/product/learning-javascript-design-patterns-
addy-osmani/
ebookname.com
https://ebookname.com/product/active-directory-field-guide-1st-
edition-laura-e-hunter/
ebookname.com
Farmers and the State in Colonial Kano Steven Pierce
https://ebookname.com/product/farmers-and-the-state-in-colonial-kano-
steven-pierce/
ebookname.com
https://ebookname.com/product/atlas-of-aids-co-infection-1st-edition-
jinxin-liu/
ebookname.com
https://ebookname.com/product/processing-and-nutrition-of-fats-and-
oils-1st-edition-ernesto-m-hernandez/
ebookname.com
https://ebookname.com/product/current-legal-issues-volume-13-law-and-
neuroscience-michael-freeman/
ebookname.com
https://ebookname.com/product/tradition-book-akashic-brotherhood-mage-
the-ascension-malcolm-sheppard/
ebookname.com
Ethics and Security Aspects of Infectious Disease Control
Interdisciplinary Perspectives 1st Edition Christian
Enemark
https://ebookname.com/product/ethics-and-security-aspects-of-
infectious-disease-control-interdisciplinary-perspectives-1st-edition-
christian-enemark/
ebookname.com
Learning JavaScript
Other resources from O’Reilly
Related titles Adding Ajax JavaScript: The Good Parts
Ajax: The Definitive Guide JavaScript: The Missing
Dojo: The Definitive Guide Manual
Dynamic DHTML: JavaScript & DHTML
The Definitive Reference Cookbook
Head First JavaScript Painting the Web
JavaScript: The Definitive
Guide
Learning JavaScript
Shelley Powers
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (http://safari.oreilly.com). For more information, contact our corporate/
institutional sales department: (800) 998-9938 or corporate@oreilly.com.
Printing History:
October 2006: First Edition.
December 2008: Second Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Learning JavaScript, the image of a baby rhino, and related trade dress are trade-
marks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
TM
ISBN: 978-0-596-52187-5
[M]
1228405087
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1. Hello JavaScript! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Hello World! 1
Hello World! Once Again 2
The script Tag 3
JavaScript Versus ECMAScript Versus JScript 5
Defining Functions in JavaScript 6
Event Handlers 7
The document Browser Object 8
The property Operator 9
The var Keyword and Scope 10
Statements 10
Comments 11
What You Didn’t See: HTML Comments and CDATA Sections 12
JavaScript Files 14
Accessibility and JavaScript Best Practices 15
Accessibility Guidelines 16
noscript 17
v
Test Your Knowledge: Quiz 36
Test Your Knowledge: Answers 37
vi | Table of Contents
5. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Declarative Functions 103
Function Naming Conventions and Size 104
Function Returns and Arguments 104
Anonymous Functions 107
Function Literals 109
Functions and Recursion 111
Nested Functions, Function Closure, and Memory Leaks 113
Callback Functions 116
Function Type Summary 118
Function Scope 119
Function As Object 120
Test Your Knowledge: Quiz 120
Test Your Knowledge: Answers 121
Table of Contents | ix
Public and Private Properties and Where this Enters the Picture 299
Getters and Setters 300
Object Encapsulation 301
Chaining Constructors and JavaScript Inheritance 308
One-Off Objects 311
Object Libraries: Packaging Your Objects for Reuse 314
Advanced Error Handling Techniques (try, throw, catch) 315
Test Your Knowledge: Quiz 318
Test Your Knowledge: Answers 319
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
x | Table of Contents
Preface
JavaScript was originally intended to be a scripting interface between a web page loaded
in the browser client (Netscape Navigator at the time) and the application on the server.
Since its introduction in 1995, JavaScript has become a key component of web devel-
opment, and has found uses elsewhere as well.
This book covers the JavaScript language, from its most primitive data types that have
been around since the beginning of the language, to its most complex features, includ-
ing those that have to do with Ajax and dynamic page effects. After reading this book,
you will have the basics you need to work with even the most sophisticated libraries
and web applications.
Audience
Readers of this book should be familiar with web page technology, including Cascading
Style Sheets (CSS) and HTML/XHTML. Previous programming experience isn’t
required, though some sections may require extra review if you have no previous
exposure to programming.
This book should help:
• Anyone who wants, or needs, to integrate JavaScript into his own personal website
or sites
• Anyone who uses a content-management tool, such as a weblogging tool, and
wants to better understand the scripting components incorporated into her tool
templates
• Web developers who seek to integrate JavaScript and some of the dynamic web
page/Ajax features into their websites
• Web service developers who want to develop for a new market of clients
• Teachers who use web technologies as either the focus or a component of their
courses
xi
• Web page designers who wish to better understand how they can enliven their
designs with interactive or animated effects
• Anyone interested in web technologies
xii | Preface
more accurate) and the browsers themselves were undergoing significant changes. For
instance, as I was in the editing phase of this book, the ECMAScript working group
announced plans to abandon work on what was known as JavaScript 2 and focus on a
new interim specification release, ECMAScript 3.1. However, most of the changes in
the newer ECMAScript aren’t implemented in many of the target browsers. In the cases
where I was relatively confident that the specification introduced a functionality that
will be implemented in future browsers, I made a note, at a minimum, of upcoming
changes.
In addition, browser makers are always introducing new versions of their tools. The
target browsers used to test examples in this book reflect the state of the browsers at
the time I wrote the book, which may not quite reflect what you’ll find when you read
the book.
However, most of the material I’ve focused on is “classic” JavaScript, which not only
is stable, but also will always form the platform on which new changes to both browser
and scripting language are based. Most, if not all, of the examples in this book should
work in older and future browsers, as well as the target browsers used to test the
examples.
Knock on wood.
Preface | xiii
Exploring the Variety of Random
Documents with Different Content
his contemplated marriage. Not to delay with moralizing, an
Evangelist by the name of Coyt made his advent into the quiet town
where Ernest lived, on the invitation of the Presbyterian church.
Great expectations had been formed by many of the more pious
brethren, who had read accounts of Dr. Coyt’s wonderful success at
other places. His services were eagerly desired and sought all over
the country.
At last he entered the little town of —— and began a series of
earnest, soul-searching sermons, which he had repeated so often
that he could frequently predict what result would follow the delivery
of each. Large, expectant congregations attended his meetings from
the very outset, since his evangelistic fame had preceded him. For
several days the preacher produced no great visible effects, and
there were scarcely any signs of spiritual life, except such as were
discernible in the numerous petitions sent in by anxious brethren,
requesting prayer for sons, daughters, wives, or other relatives and
friends. At length this request was read out to the congregation:
“Please pray for a young lawyer, who is moral and worthy in every
respect, but is lacking the one thing needful.”
Ernest was present, and heard the reading of this petition. Who
could it be but himself? At first, a flash of displeasure, to call it by
the mildest name, passed over his handsome face. Who was the
person that had the impudence to direct attention to him? But all
harsh thoughts soon passed away, when he reflected that the
petitioner, whoever it might be, desired only his good. The process
of rigid introspection succeeded his first unpleasant thoughts, and he
at once gave attention to the contest between conscience and
passion that had mysteriously begun. He seemed to be only a
spectator of the conflict of antagonistic forces in his soul. There are
times, says one of the most profound and philosophical women of
the nineteenth century, when our passions speak for us, and we
stand by and look on in astonishment. There is something similar to
this in the process of spiritual regeneration. Questions and answers
suddenly arise in the mind, as of concealed beings in whispered
consultation, and we appear to ourselves to be listening to the
mysterious dialogue. So it was with Ernest Edgefield, as he sat in the
church engaged in self-examination. It appeared to him that he had
suddenly awakened out of an alarming dream. He had been in a
moral sleep all his life, and had never reflected seriously upon the
unknown eternity which was distant but a single step. A “still small
voice” seemed to come on the very breeze, and whispered: “What
folly this young man has displayed in thinking of nothing but the
things of time and sense.” Ernest almost started. “What am I living
for?” he asked himself. “In a few weeks I shall be married, and will
give renewed attention to business. But time will flow on: and if I
live, I will soon be an old man, and I must die, and then—and then
—what?” Ernest was neither infidel nor skeptic: indeed, he only
needed that his fears should be aroused as a precedent condition to
becoming an active Christian. After prayer had been offered up for
the “young lawyer,” and while thoughts, conclusions and convictions
were all mingling together in the mind of Ernest, he looked at Clara,
who was sitting where he could see her face. Their eyes met. She
was gazing at him with an expression which he could easily
interpret, and if she had spoken in an audible voice, he could not
more clearly have understood her to say: “Isn’t it ridiculous?” The
young man almost shuddered. Why did a great yawning abyss seem
to open suddenly between them? The depression which had for
some days weighed down his spirits, all at once appeared like a
heavy rock upon his breast, causing something like a sickening
sensation to creep through his troubled heart. However, in his
present state of newly aroused emotions, to which he had been such
an utter stranger all his life, he felt that a subject of more vital
importance than even his marriage deserved his immediate
attention. Accordingly he turned his gaze upon the preacher, who
announced his text: “Thou art weighed in the balances, and art
found wanting.” Dr. Coyt, in the progress of his discourse, drew a
word-picture, upon which his audience gazed in profound, breathless
silence. No one looked upon this picture more intently than Ernest.
He saw himself alone with his Creator and the balances which were
to determine his everlasting destiny. Never before had Ernest’s
relations to time and eternity appeared in so vivid a light. The next
morning after this, as the sun kissed the glowing horizon, darkness
and doubt were dispelled from the soul of Ernest by the enlightening
beams of the Sun of Righteousness. He had found that “peace which
passeth all understanding,” and he was strangely happy.
That day, without saying a word to any one upon the subject, he
went forward to indicate his purpose of joining the church.
“Which church do you desire to join?” asked Dr. Coyt.
“I have not yet determined,” replied Ernest. “I only wish now to let it
be known that I have come out upon the Lord’s side. I intend to
investigate the doctrines of the different denominations, and I shall
join that one I like best.”
“That is right,” replied the Doctor. “Take time for reflection, so that
you will have no trouble in the future. Select that church in which
you think you can be the happiest.”
Those who feel any interest in this story will, of course, desire to
know what effect the meeting had upon Clara. Ernest had been so
absorbed in his own spiritual troubles that he had had no
conversation with her since the hour when he had become
interested upon the subject of his personal salvation. But that
evening, after he had signified his intention of attaching himself to
the church, he paid her a visit. She was not present at the morning
service, and knew nothing of the step he had taken. After the
exchange of ordinary civilities, she said with a significant flippancy
which was chilling to Ernest’s heart:
“How have you enjoyed the show?”
“Show!” exclaimed Ernest, bestowing upon her a solemn look of
inquiry.
“Yes,” said Clara, not seeming to notice his serious air. “It is as good
as any show. Wasn’t it funny to have them all praying for you?”
“I do not see where there was any fun,” said Ernest with an
expression of disappointment upon his face, “and I am truly sorry to
hear you talk so lightly about such solemn things. They are too
sacred to admit of sport.”
“So, they have got you, too, have they?” asked Clara, breaking into a
merry laugh. “Well, I confess I am astonished.”
“Why should you be? I cannot see that it is a matter of such
profound amazement for a man to join the church.”
“Have you really joined the church?”
“I have, or at least gave notice this morning that I would do so, and
I earnestly wish, my dear Clara, that you would make up your mind
to the same thing. That is needed to complete our happiness.”
She made no reply, but laughed in a tone which it would have
required no expert physiognomist to pronounce one of derision.
“What is it that is so amusing?” asked Ernest in vexation. “I had
hoped that you would talk seriously about this matter of such vital
importance.”
“The idea of my joining the church, and giving up my dancing and all
other amusements, is simply preposterous. It is funny.”
“But suppose you were to die,” said Ernest, “what would become of
you? Are you willing to sacrifice your soul for a few worldly pleasures
which, after all, add nothing to your happiness?”
“Why, are you going to turn preacher, too?” said Clara with an
amused expression. “That’s just the way Dr. Coyt has been
preaching for the last five or six days.”
“I am no preacher, and never expect to be,” replied Ernest, “but that
is no reason why I should not want my friends saved, especially such
a friend as you will be.”
Clara bit her cherry nether lip, and laying aside her mood of levity,
said:
“I should like to know what we are to do in this world, if we are
forbidden to enjoy life. That is what I dislike about religious people.
They are so gloomy, and can talk about nothing but death. I hate to
be with them.”
This was spoken in such a way as to cause Ernest to see again the
yawning chasm gaping between them.
“O, my dear Clara!” he exclaimed with trembling tenderness, “how
you are mistaken!”
“Why, how do you know?” she asked in surprise. “You have not been
one of them long enough to find out, I should think. How did you
become so wise, all of a sudden?”
Ernest was not at all pleased with the manner in which she
addressed him, but he durst not manifest the least vexation in the
critical juncture of his amatory affairs. He felt that a quarrel might
terminate in a final overthrow of the fond hopes upon which his
heart had fed for months past. He, therefore, spoke as mildly and
affectionately as possible:
“I have learned something about it even in the last few hours. I have
never experienced such a sense of love, joy and peace in all my
previous life. I am astonished at myself for never having turned my
attention sooner to eternal things. All these years, since I reached
the line of moral responsibility, have been almost wasted, or, at
least, the spiritual enjoyments of all this time have been lost to me;
and how I regret it!”
“How you do talk!” exclaimed Clara. “Do you expect to keep up such
lecturing all our lives? If you do, we may as well—”
“May as well what?” asked Ernest with a sinking heart.
“May as well follow divergent paths,” she said with a timidity which
implied that she, by no means, desired the proposition to be
accepted.
“No, my dear Clara, I shall not mention it again if it is unpleasant to
you. I shall leave you in the hands of God and continue to pray for
you. I think you will take a different view of the matter after a
while.”
“But I would as soon you would talk to me as to look at me as if I
were a criminal.”
“I do not think,” said Ernest, “that religion will convert me into a
long-faced monk. On the contrary, I expect to be more cheerful and
happy than I could be otherwise. You are the one to look solemn
and gloomy.”
“You expect,” said Clara, not appearing to notice the last remark,
“you expect to give up dancing, as most church people do.”
“Certainly. I cannot do violence to my conscience by indulging in an
amusement which I regard as of doubtful propriety, to say the least
of it.”
“Where is the harm in dancing? Church people condemn it, but I
never could see any sin in it—not the least.”
“But there would be sin in it to me with my present views,” said
Ernest.
“You used to like it as well as I did.”
“Yes, that is true; but the time has come when I must and will
renounce it.”
“You expect me to give it up, too?”
“That is a matter to be determined by your own conscience. I shall
not interfere.”
“There is the theatre—you will give that up too?”
“I feel that I must do that, too.”
“Then,” said Clara with a slight frown, “what congeniality of taste
and pursuits is there between us?”
“Why, my loved one,” said Ernest with a smile, “fortunately theatres
and dances occupy but a small portion of our time.”
“Who will escort me when I want to go?”
Ernest loved his affianced with such an intensity that he dreaded to
get into an unpleasant controversy that might culminate fatally to his
hopes. If he were too puritanical and inflexible, he thought, she
might sever all the ties between them—an event which made him
shudder to contemplate; so he replied:
“All congeniality of taste between us need not be destroyed because
you may fancy some amusements which I do not. It could scarcely
be expected that two human beings should think exactly alike. With
regard to your dancing, I leave it to your conscience and to time
which usually destroys our relish for most of the sports and
enjoyments of youth. I have strong hopes that you will sooner or
later perceive the necessity of leaving the paths of moral ruin and
renouncing the pleasures of sin for the more solid and substantial
pleasures of religion.”
Clara said nothing, but sat still gazing into the forest which spread
out in the distance—gazing with that vacant air which indicates the
absence of attention to any object upon which her eyes might be
fixed. Ernest could form no idea as to the character of her thoughts
from the expression of her fair countenance, and he began to fear
that he had said too much, and thought that perhaps he would
better endeavor to remove every difficulty that might prove an
obstacle to their union. He did not want to leave any grounds for
one of those unfortunate misunderstandings between lovers which
so frequently grow out of nothing. He therefore said with an air of
cheerfulness and tenderness:
“You need not suppose, my loved one, that I will be forever
preaching to you. That is not my calling. Have I given you offence by
anything I have said? I mean by all I have said only that there is a
time for all things—a time to dance and a time to give religion a
prominent place in our thoughts.”
“O, no; I’m not offended, but you make me feel gloomy. It is bad
enough to hear these things about death at church, where we
expect it. I didn’t know that we had to make religion a topic of
private conversation.”
“No, we are not forced to do so; but I thought it a suitable time to
talk about it now when the subject is occupying the attention of the
whole community.”
“I candidly confess I don’t like to talk about such things,” said Clara
with a serious air. “I have always had a sort of horror of religion. In
my mind it is associated with death and other disagreeable things.”
“But these disagreeable things,” said Ernest, “as you call them, are
stubborn realities which we cannot avoid. Sooner or later, we must
face them, whether we like or not. Would we not, then, better
regulate our lives so that these very gloomy things shall become
sources of pleasure?”
“O, I suppose so,” said Clara dryly, “if death could ever be a pleasant
subject of conversation.”
“Not long since,” replied Ernest with the deepest solemnity, “I
entertained the very same views which you do. I would not think
about death when I could possibly banish it from my mind, and I
contemplated it for an instant as some horrible monster which I
must face after a while. I regarded it with as much dread as ever the
celebrated Dr. Samuel Johnson did. But now,” and as he spoke an
expression of deep joy flashed over his features, “I do not dread the
event as such an awful calamity. I even love to think about it.”
“What! do you want to die?” cried Clara.
“No: I did not say that,” calmly replied Ernest.
“No man in the enjoyment of health really desires to die; for in some
respects, it is a terrible ordeal from which poor, weak human nature
shrinks. I have no disposition to court death: I want to live for your
sake, for you know with what depth and intensity I love you, and
loving you thus, I should like, above all things, to see you in a
condition that would enable you to exclaim with rapture, ‘O death,
where is thy sting? O grave, where is thy victory?’ What a happy
thought to me that we should be one on earth, and then when we
cross over the dark river, our purified souls should be knit together in
the bonds of a higher, nobler affection than is possible here; and
then that we should stroll hand-in-hand in the heavenly groves,
along the banks of the crystal river, under the fruit trees whose
leaves are for the healing of the nations, never more to be disturbed
by any misapprehensions, nor even by a discordant word or thought.
We shall be one in heart, soul and mind. This is what I call true
marriage. It is a contract not to end with time, but it goes on
through the numberless ages of eternity. O, what a glorious
prospect!” he exclaimed with features lit up with pure, holy joy; and
then he paused for an instant as if overwhelmed and lost in the
contemplation of indescribable scenes which “eye hath not seen nor
ear heard, neither have entered into the heart of man.” After a
moment he continued: “On the other hand, what an awful thought!
It makes me shudder. O, if you remain as you now are, we shall be
separated forever, when we part at the grave. Then where will you
go? If you miss the glory-land, there is only one more place—the
lake that burns with fire and brimstone—a place where their worm
dieth not and the fire is not quenched. If there is no fire there, as
some contend, then it is a place of black, thick darkness. The lost
soul, cast out into the illimitable regions of uninhabited space, away
beyond the last star that glitters on the outskirts of visible creation,
will go wandering round and round, or if too weary to make an
effort, it will begin falling, like a bird with folded wings, and keep on
falling, falling, down and down, forever down—no company but your
own thoughts—no sound heard but your own breathing—no sweet
music—no voice of friend—no light—nothing but the horrors of
eternal, impenetrable darkness. You may suppose you will have
companions—but what will be their character? Not kind friends, to
speak words of consolation, but malevolent fiends whose delight it
will be to torment. All the horrors so graphically described by Dante
may be awful realities. Can you blame me, then, for feeling the
deepest anxiety on your account? I should be the happiest man in
town if you could make up your mind to join the church.”
“O, I could not think of such a thing!” exclaimed Clara. “You have
already given me the blues. I fear you will never be yourself again.
You are so changed. But reading that awful old Dante is enough to
frighten any one out of his senses. I tried to read it not long since,
but it was so foolish and absurd, I dropped it in disgust. But haven’t
you preached long enough? I do believe you will be a preacher yet.”
“No; I have no such idea as that. But I should be sorry to think that
preachers are the only persons to whom it is allowable to talk about
religion. However, I am a changed man, and I am glad you can
perceive it. I hope I may never again be the wicked man I have
been. But I shall not further press the subject upon your attention,
and I promise not to mention it again till you are in the proper mood
to talk about it.”
The foregoing conversation is no integral part of the present story,
and might have been omitted entirely, but we have recorded it at
length to show what different views young people entertain in
regard to the highest destiny a human being can achieve. What
makes such a vast difference, when there are precisely the same
incentives to action in both? Some quickly cut the Gordian knot by
attributing it to the difference in their wills, which, we may bring this
chapter to an end by saying, is quite a convenient way of avoiding
Deep Waters.
CHAPTER III.
A RIVAL.