JavaScript Definitive Guide 6th Edition
JavaScript Definitive Guide 6th Edition
SIXTH EDITION
’DYLG)ODQDJDQ
JavaScript: The Definitive Guide, Sixth Edition
by David Flanagan
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
This book is dedicated to all who teach peace
and resist violence.
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
1. Introduction to JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Core JavaScript 4
1.2 Client-Side JavaScript 8
2. Lexical Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1 Character Set 21
2.2 Comments 23
2.3 Literals 23
2.4 Identifiers and Reserved Words 23
2.5 Optional Semicolons 25
5. Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.1 Expression Statements 88
5.2 Compound and Empty Statements 88
5.3 Declaration Statements 89
5.4 Conditionals 92
5.5 Loops 97
5.6 Jumps 102
5.7 Miscellaneous Statements 108
5.8 Summary of JavaScript Statements 112
6. Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
6.1 Creating Objects 116
6.2 Querying and Setting Properties 120
6.3 Deleting Properties 124
6.4 Testing Properties 125
6.5 Enumerating Properties 126
6.6 Property Getters and Setters 128
6.7 Property Attributes 131
6.8 Object Attributes 135
6.9 Serializing Objects 138
6.10 Object Methods 138
7. Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
7.1 Creating Arrays 141
7.2 Reading and Writing Array Elements 142
7.3 Sparse Arrays 144
7.4 Array Length 144
7.5 Adding and Deleting Array Elements 145
7.6 Iterating Arrays 146
7.7 Multidimensional Arrays 148
7.8 Array Methods 148
7.9 ECMAScript 5 Array Methods 153
7.10 Array Type 157
8. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.1 Defining Functions 164
8.2 Invoking Functions 166
8.3 Function Arguments and Parameters 171
8.4 Functions As Values 176
8.5 Functions As Namespaces 178
8.6 Closures 180
8.7 Function Properties, Methods, and Constructor 186
8.8 Functional Programming 191
Table of Contents | ix
Part II. Client-Side JavaScript
x | Table of Contents
17.2 Registering Event Handlers 456
17.3 Event Handler Invocation 460
17.4 Document Load Events 465
17.5 Mouse Events 467
17.6 Mousewheel Events 471
17.7 Drag and Drop Events 474
17.8 Text Events 481
17.9 Keyboard Events 484
Table of Contents | xi
22.5 Typed Arrays and ArrayBuffers 687
22.6 Blobs 691
22.7 The Filesystem API 700
22.8 Client-Side Databases 705
22.9 Web Sockets 712
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1019
This book covers the JavaScript language and the JavaScript APIs implemented by web
browsers. I wrote it for readers with at least some prior programming experience who
want to learn JavaScript and also for programmers who already use JavaScript but want
to take their understanding to a new level and really master the language and the web
platform. My goal with this book is to document the JavaScript language and platform
comprehensively and definitively. As a result, this is a large and detailed book. My hope,
however, is that it will reward careful study, and that the time you spend reading it will
be easily recouped in the form of higher programming productivity.
This book is divided into four parts. Part I covers the JavaScript language itself.
Part II covers client-side JavaScript: the JavaScript APIs defined by HTML5 and related
standards and implemented by web browsers. Part III is the reference section for the
core language, and Part IV is the reference for client-side JavaScript. Chapter 1 includes
an outline of the chapters in Parts I and II (see §1.1).
This sixth edition of the book covers both ECMAScript 5 (the latest version of the core
language) and HTML5 (the latest version of the web platform). You’ll find
ECMAScript 5 material throughout Part I. The new material on HTML5 is mostly in
the chapters at the end of Part II, but there is also some in other chapters as well.
Completely new chapters in this edition include Chapter 11, JavaScript Subsets and
Extensions; Chapter 12, Server-Side JavaScript; Chapter 19, The jQuery Library; and
Chapter 22, HTML5 APIs.
Readers of previous editions may notice that I have completely rewritten many of the
chapters in this book for the sixth edition. The core of Part I—the chapters covering
objects, arrays, functions, and classes—is all new and brings the book in line with
current programming styles and best practices. Similarly, key chapters of Part II, such
as those covering documents and events, have been completely rewritten to bring them
up-to-date.
xiii
A Note About Piracy
If you are reading a digital version of this book that you (or your employer) did not pay
for (or borrow from someone who did) then you probably have an illegally pirated copy.
Writing the sixth edition of this book was a full-time job, and it took more than a year.
The only way I get paid for that time is when readers actually buy the book. And the
only way I can afford to work on a seventh edition is if I get paid for the sixth.
I do not condone piracy, but if you have a pirated copy, go ahead and read a couple of
chapters. I think that you’ll find that this is a valuable source of information about
JavaScript, better organized and of higher quality than what you can find freely (and
legally) available on the Web. If you agree that this is a valuable source of information,
then please pay for that value by purchasing a legal copy (either digital or print) of the
book. On the other hand, if you find that this book is no more valuable than the free
information on the web, then please discard your pirated copy and use those free
information sources.
Example Code
The examples in this book are available online. You can find them linked from the
book’s catalog page at the publisher’s website:
[Link]
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact O’Reilly
for permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
xiv | Preface
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
If you use the code from this book, I appreciate, but do not require, attribution. An
attribution usually includes the title, author, publisher, and ISBN. For example: “Java-
Script: The Definitive Guide, by David Flanagan (O’Reilly). Copyright 2011 David Fla-
nagan, 978-0-596-80552-4.”
For more details on the O’Reilly code reuse policy, see [Link]
ask_tim/2001/[Link]. If you feel your use of the examples falls outside of the
permission given above, feel free to contact O’Reilly at permissions@[Link].
Acknowledgments
Many people have helped me with the creation of this book. I’d like to thank my editor,
Mike Loukides, for trying to keep me on schedule and for his insightful comments.
Thanks also to my technical reviewers: Zachary Kessin, who reviewed many of the
chapters in Part I, and Raffaele Cecco, who reviewed Chapter 19 and the <canvas>
material in Chapter 21. The production team at O’Reilly has done their usual fine job:
Dan Fauxsmith managed the production process, Teresa Elsey was the production
editor, Rob Romano drew the figures, and Ellen Troutman Zaig created the index.
In this era of effortless electronic communication, it is impossible to keep track of all
those who influence and inform us. I’d like to thank everyone who has answered my
questions on the es5, w3c, and whatwg mailing lists, and everyone who has shared their
insightful ideas about JavaScript programming online. I’m sorry I can’t list you all by
Preface | xv
name, but it is a pleasure to work within such a vibrant community of JavaScript
programmers.
Editors, reviewers, and contributors to previous editions of this book have included:
Andrew Schulman, Angelo Sirigos, Aristotle Pagaltzis, Brendan Eich, Christian
Heilmann, Dan Shafer, Dave C. Mitchell, Deb Cameron, Douglas Crockford, Dr.
Tankred Hirschmann, Dylan Schiemann, Frank Willison, Geoff Stearns, Herman Ven-
ter, Jay Hodges, Jeff Yates, Joseph Kesselman, Ken Cooper, Larry Sullivan, Lynn Roll-
ins, Neil Berkman, Nick Thompson, Norris Boyd, Paula Ferguson, Peter-Paul Koch,
Philippe Le Hegaret, Richard Yaker, Sanders Kleinfeld, Scott Furman, Scott Issacs,
Shon Katzenberger, Terry Allen, Todd Ditchendorf, Vidur Apparao, and Waldemar
Horwat.
This edition of the book is substantially rewritten and kept me away from my family
for many late nights. My love to them and my thanks for putting up with my absences.
— David Flanagan ([Link]), March 2011
xvi | Preface
CHAPTER 1
Introduction to JavaScript
1
JavaScript: Names and Versions
JavaScript was created at Netscape in the early days of the Web, and technically, “Java-
Script” is a trademark licensed from Sun Microsystems (now Oracle) used to describe
Netscape’s (now Mozilla’s) implementation of the language. Netscape submitted the
language for standardization to ECMA—the European Computer Manufacturer’s As-
sociation—and because of trademark issues, the standardized version of the language
was stuck with the awkward name “ECMAScript.” For the same trademark reasons,
Microsoft’s version of the language is formally known as “JScript.” In practice, just
about everyone calls the language JavaScript. This book uses the name “ECMAScript”
only to refer to the language standard.
For the last decade, all web browsers have implemented version 3 of the ECMAScript
standard and there has really been no need to think about version numbers: the lan-
guage standard was stable and browser implementations of the language were, for the
most part, interoperable. Recently, an important new version of the language has been
defined as ECMAScript version 5 and, at the time of this writing, browsers are beginning
to implement it. This book covers all the new features of ECMAScript 5 as well as all
the long-standing features of ECMAScript 3. You’ll sometimes see these language ver-
sions abbreviated as ES3 and ES5, just as you’ll sometimes see the name JavaScript
abbreviated as JS.
When we’re speaking of the language itself, the only version numbers that are relevant
are ECMAScript versions 3 or 5. (Version 4 of ECMAScript was under development
for years, but proved to be too ambitious and was never released.) Sometimes, however,
you’ll also see a JavaScript version number, such as JavaScript 1.5 or JavaScript 1.8.
These are Mozilla’s version numbers: version 1.5 is basically ECMAScript 3, and later
versions include nonstandard language extensions (see Chapter 11). Finally, there are
also version numbers attached to particular JavaScript interpreters or “engines.” Goo-
gle calls its JavaScript interpreter V8, for example, and at the time of this writing the
current version of the V8 engine is 3.0.
To be useful, every language must have a platform or standard library or API of func-
tions for performing things like basic input and output. The core JavaScript language
defines a minimal API for working with text, arrays, dates, and regular expressions but
does not include any input or output functionality. Input and output (as well as more
sophisticated features, such as networking, storage, and graphics) are the responsibility
of the “host environment” within which JavaScript is embedded. Usually that host
environment is a web browser (though we’ll see two uses of JavaScript without a web
browser in Chapter 12). Part I of this book covers the language itself and its minimal
built-in API. Part II explains how JavaScript is used in web browsers and covers the
sprawling browser-based APIs loosely known as “client-side JavaScript.”
Part III is the reference section for the core API. You can read about the JavaScript array
manipulation API by looking up “Array” in this part of the book, for example.
Part IV is the reference section for client-side JavaScript. You might look up “Canvas”
Exploring JavaScript
When learning a new programming language, it’s important to try the examples in the
book, and then modify them and try them again to test your understanding of the
language. To do that, you need a JavaScript interpreter. Fortunately, every web browser
includes a JavaScript interpreter, and if you’re reading this book, you probably already
have more than one web browser installed on your computer.
We’ll see later on in this chapter that you can embed JavaScript code within <script>
tags in HTML files, and when the browser loads the file, it will execute the code. For-
tunately, however, you don’t have to do that every time you want to try out simple
snippets of JavaScript code. Spurred on by the powerful and innovative Firebug exten-
sion for Firefox (pictured in Figure 1-1 and available for download from [Link]
.com/), today’s web browsers all include web developer tools that are indispensable for
debugging, experimenting, and learning. You can usually find these tools in the Tools
menu of the browser under names like “Developer Tools” or “Web Console.”
(Firefox 4 includes a built-in “Web Console,” but at the time of this writing, the Firebug
extension is better.) Often, you can call up a console with a keystroke like F12 or Ctrl-
Shift-J. These console tools often appear as panes at the top or bottom of the browser
window, but some allow you to open them as separate windows (as pictured in Fig-
ure 1-1), which is often quite convenient.
A typical “developer tools” pane or window includes multiple tabs that allow you to
inspect things like HTML document structure, CSS styles, network requests, and so
on. One of the tabs is a “JavaScript console” that allows you to type in lines of JavaScript
code and try them out. This is a particularly easy way to play around with JavaScript,
and I recommend that you use it as you read this book.
There is a simple console API that is portably implemented by modern browsers. You
can use the function [Link]() to display text on the console. This is often sur-
prisingly helpful while debugging, and some of the examples in this book (even in the
core language section) use [Link]() to perform simple output. A similar but more
intrusive way to display output or debugging messages is by passing a string of text to
the alert() function, which displays it in a modal dialog box.
Introduction to JavaScript | 3
Figure 1-1. The Firebug debugging console for Firefox