Tải bản đầy đủ (.pdf) (809 trang)

wrox press professional javascript for web developers 2nd (2009)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.72 MB, 809 trang )

Professional
JavaScript
®
for Web Developers
2nd Edition
Nicholas C. Zakas
Wiley Publishing, Inc.
ffirs.indd vffirs.indd v 12/8/08 12:02:06 PM12/8/08 12:02:06 PM
Professional JavaScript
®
for Web Developers, 2nd Edition
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-22780-0
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data
Zakas, Nicholas C.
Professional JavaScript for web developers/Nicholas C. Zakas. — 2nd ed.
p. cm.
Includes index.
ISBN 978-0-470-22780-0 (paper/website)
1. Web site development. 2. JavaScript (Computer program language) I. Title.
TK5105.8885.J38Z34 2008
005.2'762 — dc22
2008045552


No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by
any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted
under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written
permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.
Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley &
Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at
/>Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or
warranties with respect to the accuracy or completeness of the contents of this work and specifically
disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No
warranty may be created or extended by sales or promotional materials. The advice and strategies contained
herein may not be suitable for every situation. This work is sold with the understanding that the publisher is
not engaged in rendering legal, accounting, or other professional services. If professional assistance is
required, the services of a competent professional person should be sought. Neither the publisher nor the
author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in
this work as a citation and/or a potential source of further information does not mean that the author or the
publisher endorses the information the organization or Web site may provide or recommendations it may
make. Further, readers should be aware that Internet Web sites listed in this work may have changed or
disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department
within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related
trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the
United States and other countries, and may not be used without written permission. JavaScript is a
registered trademark of Sun Microsystems, Inc. All other trademarks are the property of their respective
owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not
be available in electronic books.
ffirs.indd viffirs.indd vi 12/8/08 12:02:07 PM12/8/08 12:02:07 PM
Contents

Foreword xxvii
Introduction xxix
Chapter 1: What Is JavaScript? 1
A Short History 1
JavaScript Implementations 3
ECMAScript 3
The Document Object Model (DOM) 7
The Browser Object Model (BOM) 9
JavaScript Versions 10
Summary 11
Chapter 2: JavaScript in HTML 13
The <script> Element 13
Tag Placement 15
Deferred Scripts 16
Changes in XHTML 17
Deprecated Syntax 18
Inline Code versus External Files 19
Document Modes 19
The <noscript> Element 21
Summary 22
Chapter 3: Language Basics 23
Syntax 23
Case-sensitivity 23
Identifiers 24
Comments 24
Statements 25
Keywords and Reserved Words 25
Variables 26
Data Types 28
The typeof Operator 28

The Undefined Type 28
The Null Type 30
ftoc.indd xvftoc.indd xv 12/8/08 12:01:07 PM12/8/08 12:01:07 PM
Contents
xvi

The Boolean Type 30
The Number Type 31
The String Type 37
The Object Type 40
Operators 41
Unary Operators 41
Bitwise Operators 45
Boolean Operators 51
Multiplicative Operators 54
Additive Operators 56
Relational Operators 58
Equality Operators 60
Conditional Operator 62
Assignment Operators 62
Comma Operator 63
Statements 63
The if Statement 63
The do-while Statement 64
The while Statement 65
The for Statement 65
The for-in Statement 66
Labeled Statements 67
The break and continue Statements 67
The with Statement 69

The switch Statement 70
Functions 72
Understanding Arguments 74
No Overloading 76
Summary 76
Chapter 4: Variables, Scope, and Memory 79
Primitive and Reference Values 79
Dynamic Properties 80
Copying Values 81
Argument Passing 82
Determining Type 84
Execution Context and Scope 84
Scope Chain Augmentation 87
No Block-Level Scopes 88
ftoc.indd xviftoc.indd xvi 12/8/08 12:01:07 PM12/8/08 12:01:07 PM
Contents
xvii
Garbage Collection 90
Mark-and-Sweep 91
Reference Counting 91
Performance 93
Managing Memory 93
Summary 94
Chapter 5: Reference Types 97
The Object Type 97
The Array Type 100
Conversion Methods 102
Stack Methods 104
Queue Methods 105
Reordering Methods 106

Manipulation Methods 108
The Date Type 109
Inherited Methods 111
Date-Formatting Methods 112
Date/Time Component Methods 113
The RegExp Type 115
RegExp Instance Properties 117
RegExp Instance Methods 118
RegExp Constructor Properties 120
Pattern Limitations 122
The Function Type 122
No Overloading (Revisited) 123
Function Declarations vs. Function Expressions 124
Functions as Values 125
Function Internals 126
Function Properties and Methods 128
Primitive Wrapper Types 130
The Boolean Type 131
The Number Type 132
The String Type 134
Built-in Objects 142
The Global Object 142
The Math Object 146
Summary 149
ftoc.indd xviiftoc.indd xvii 12/8/08 12:01:07 PM12/8/08 12:01:07 PM
Contents
xviii
Chapter 6: Object-Oriented Programming 151
Creating Objects 151
The Factory Pattern 152

The Constructor Pattern 152
The Prototype Pattern 155
Combination Constructor/Prototype Pattern 166
Dynamic Prototype Pattern 166
Parasitic Constructor Pattern 167
Durable Constructor Pattern 169
Inheritance 170
Prototype Chaining 170
Constructor Stealing 175
Combination Inheritance 176
Prototypal Inheritance 177
Parasitic Inheritance 178
Parasitic Combination Inheritance 179
Summary 182
Chapter 7: Anonymous Functions 183
Recursion 184
Closures 185
Closures and Variables 188
The this Object 189
Memory Leaks 190
Mimicking Block Scope 191
Private Variables 193
Static Private Variables 195
The Module Pattern 196
The Module-Augmentation Pattern 198
Summary 199
Chapter 8: The Browser Object Model 201
The window Object 201
The Global Scope 201
Window Relationships and Frames 202

Window Position 205
Window Size 206
Navigating and Opening Windows 207
Intervals and Timeouts 211
System Dialogs 213
ftoc.indd xviiiftoc.indd xviii 12/8/08 12:01:08 PM12/8/08 12:01:08 PM
Contents
xix
The location Object 216
Query String Arguments 216
Manipulating the Location 217
The navigator Object 219
Detecting Plug-ins 221
Registering Handlers 223
The screen Object 224
The history Object 226
Summary 227
Chapter 9: Client Detection 229
Capability Detection 229
Quirks Detection 231
User-Agent Detection 232
History 233
Working with User-Agent Detection 240
The Complete Script 255
Usage 258
Summary 258
Chapter 10: The Document Object Model 261
Hierarchy of Nodes 261
The Node Type 263
The Document Type 269

The Element Type 279
The Text Type 289
The Comment Type 292
The CDATASection Type 293
The DocumentType Type 294
The DocumentFragment Type 294
The Attr Type 296
DOM Extensions 297
Rendering Modes 297
Scrolling 298
The children Property 298
The contains() Method 299
Content Manipulation 300
Working with the DOM 307
Dynamic Scripts 307
Dynamic Styles 309
ftoc.indd xixftoc.indd xix 12/8/08 12:01:08 PM12/8/08 12:01:08 PM
Contents
xx
Manipulating Tables 311
Using NodeLists 314
Summary 314
Chapter 11: DOM Levels 2 and 3 317
DOM Changes 317
XML Namespaces 318
Other Changes 322
Styles 326
Accessing Element Styles 326
Working with Style Sheets 331
Element Dimensions 336

Traversals 342
NodeIterator 344
TreeWalker 347
Ranges 349
Ranges in the DOM 349
Ranges in Internet Explorer 358
Summary 362
Chapter 12: Events 365
Event Flow 365
Event Bubbling 366
Event Capturing 367
DOM Event Flow 367
Event Handlers or Listeners 368
HTML Event Handlers 368
DOM Level 0 Event Handlers 369
DOM Level 2 Event Handlers 370
Internet Explorer Event Handlers 372
Cross-Browser Event Handlers 373
The Event Object 375
The DOM Event Object 375
The Internet Explorer Event Object 379
Cross-Browser Event Object 381
Event Types 383
UI Events 383
Mouse Events 383
Keyboard Events 392
HTML Events 397
ftoc.indd xxftoc.indd xx 12/8/08 12:01:08 PM12/8/08 12:01:08 PM
Contents
xxi

Mutation Events 402
Proprietary Events 407
Mobile Safari Events 417
Memory and Performance 422
Event Delegation 422
Removing Event Handlers 424
Simulating Events 425
DOM Event Simulation 426
Internet Explorer Event Simulation 430
Summary 432
Chapter 13: Scripting Forms 433
Form Basics 433
Submitting Forms 434
Resetting Forms 435
Form Fields 436
Scripting Text Boxes 441
Text Selection 442
Input Filtering 445
Automatic Tab Forward 449
Scripting Select Boxes 450
Options Selection 452
Adding Options 454
Removing Options 455
Moving and Reordering Options 455
Form Serialization 456
Rich Text Editing 458
Interacting with Rich Text 459
Rich Text Selections 462
Rich Text in Forms 463
Summary 464

Chapter 14: Error Handling and Debugging 465
Browser Error Reporting 465
Internet Explorer 465
Firefox 467
Safari 469
Opera 470
Chrome 472
ftoc.indd xxiftoc.indd xxi 12/8/08 12:01:08 PM12/8/08 12:01:08 PM
Contents
xxii
Error Handling 473
The try-catch Statement 474
Throwing Errors 477
The error Event 480
Error-Handling Strategies 481
Identify Where Errors Might Occur 481
Distinguishing between Fatal and Nonfatal Errors 486
Log Errors to the Server 487
Debugging Techniques 488
Logging Messages to a Console 488
Logging Messages to the Page 491
Throwing Errors 491
Common Internet Explorer Errors 492
Operation Aborted 493
Invalid Character 494
Member Not Found 494
Unknown Runtime Error 495
Syntax Error 495
The System Cannot Locate the Resource Specified 496
Debugging Tools 496

Internet Explorer Debugger 496
Firebug 502
Drosera 507
Opera JavaScript Debugger 510
Other Options 513
Summary 513
Chapter 15: XML in JavaScript 515
XML DOM Support in Browsers 515
DOM Level 2 Core 515
The DOMParser Type 516
The XMLSerializer Type 517
DOM Level 3 Load and Save 518
Serializing XML 523
XML in Internet Explorer 523
Cross-Browser XML Processing 528
XPath Support in Browsers 530
DOM Level 3 XPath 530
XPath in Internet Explorer 535
Cross-Browser XPath 536
ftoc.indd xxiiftoc.indd xxii 12/8/08 12:01:08 PM12/8/08 12:01:08 PM
Contents
xxiii
XSLT Support in Browsers 539
XSLT in Internet Explorer 539
The XSLTProcessor Type 543
Cross-Browser XSLT 545
Summary 546
Chapter 16: ECMAScript for XML 547
E4X Types 547
The XML Type 547

The XMLList Type 549
The Namespace Type 550
The QName Type 551
General Usage 552
Accessing Attributes 553
Other Node Types 555
Querying 556
XML Construction and Manipulation 558
Parsing and Serialization Options 560
Namespaces 561
Other Changes 563
Enabling Full E4X 564
Summary 564
Chapter 17: Ajax and JSON 567
The XHR Object 568
XHR Usage 569
HTTP Headers 571
GET Requests 573
POST Requests 574
Browser Differences 575
Security 577
Cross-Domain Requests 578
The XDomainRequest Object 578
Cross-Domain XHR 580
JSON 581
Using JSON with Ajax 583
Security 586
Summary 587
ftoc.indd xxiiiftoc.indd xxiii 12/8/08 12:01:09 PM12/8/08 12:01:09 PM
Contents

xxiv
Chapter 18: Advanced Techniques 589
Advanced Functions 589
Scope-Safe Constructors 589
Lazy Loading Functions 592
Function Binding 594
Function Currying 596
Advanced Timers 598
Repeating Timers 600
Yielding Processes 602
Function Throttling 604
Custom Events 606
Drag-and-Drop 609
Fixing Drag Functionality 611
Adding Custom Events 613
Summary 615
Chapter 19: Client-Side Storage 617
Cookies 617
Restrictions 618
Cookie Parts 618
Cookies in JavaScript 619
Subcookies 622
Cookie Considerations 626
Internet Explorer User Data 627
DOM Storage 628
The Storage Type 628
The sessionStorage Object 629
The globalStorage Object 631
The localStorage Object 632
The StorageItem Type 633

The storage Event 633
Limits and Restrictions 634
Summary 634
Chapter 20: Best Practices 635
Maintainability 635
What is Maintainable Code? 636
Code Conventions 636
Loose Coupling 639
Programming Practices 642
ftoc.indd xxivftoc.indd xxiv 12/8/08 12:01:09 PM12/8/08 12:01:09 PM
Contents
xxv
Performance 647
Be Scope-Aware 648
Choose the Right Approach 650
Minimize Statement Count 655
Optimize DOM Interactions 657
Deployment 660
Build Process 660
Validation 662
Compression 663
Summary 666
Chapter 21: Upcoming APIs 669
The Selectors API 669
The querySelector() Method 670
The querySelectorAll() Method 671
Support and the Future 672
HTML 5 672
Character Set Properties 672
Class-Related Additions 673

Custom Data Attributes 675
Cross-Document Messaging 676
Media Elements 677
The <canvas> Element 682
Offline Support 692
Changes to History 693
Database Storage 694
Drag-and-Drop 696
The WebSocket Type 700
The Future of HTML 5 701
Summary 702
Chapter 22: The Evolution of JavaScript 703
ECMAScript 4/JavaScript 2 703
JavaScript 1.5 704
JavaScript 1.6 706
JavaScript 1.7 709
JavaScript 1.8 714
JavaScript 1.9 717
ECMAScript 4 Proposals 717
Variable Typing 717
ftoc.indd xxvftoc.indd xxv 12/8/08 12:01:09 PM12/8/08 12:01:09 PM
Contents
xxvi
Functions 720
Defining Types 723
Classes and Interfaces 726
Interfaces 730
Inheritance 730
Namespaces 732
Packages 734

Other Language Changes 734
The Future of ECMAScript 4 741
ECMAScript 3.1 741
Changes to Object Internals 741
Static Object Methods 742
Object Creation 744
Changes to Functions 748
Native JSON Support 750
Decimals 752
Usage Subsets 756
The Future of ECMAScript 3.1 757
Summary 757
Appendix A: JavaScript Libraries 759
Appendix B: JavaScript Tools 765
Index 773
ftoc.indd xxviftoc.indd xxvi 12/8/08 12:01:09 PM12/8/08 12:01:09 PM
Foreword
JavaScript, for much of its existence, has been the subject of fear, invective, disdain, and
misunderstanding. In its early years, many “serious programmers” thought that JavaScript wasn’t
serious enough.
By contrast, many liberal arts majors drafted into web-developer service during the dotcom boom
thought JavaScript was mysterious and arcane. Many who had both the tenacity and the patience to fully
grok JavaScript as a language were nevertheless frustrated by its inconsistent implementation across
competing browsers. All of these factors helped lead to a proliferation of awkward and poorly conceived
scripts. And, through the extraordinary openness of front-end code on the Web, a lot of bad habits were
copied from one site and pasted into the source of another. Thus JavaScript’s bad reputation as a
language, which was generally ill-deserved, became intertwined with a deservedly bad reputation
surrounding its implementations.
Around 2001 (with the release of Internet Explorer 6), improved browser implementations and
improving practice in web development began to converge. The

XMLHttpRequest object at the heart of
Ajax was slowly being discovered, and a new paradigm of desktop-style user interaction was emerging
within the browser. The DOM APIs that allowed JavaScript to manipulate the structure and content of
web documents had solidified. CSS, for all the contortions, omissions, and the willful insanity of its
implementations by browser vendors, had progressed far enough that beauty and responsiveness could
be combined with the Web’s new interactive power. As a result, JavaScript became the subject of a new
set of emotions: surprise, delight, and awe. If you think back to the first time you used Google Maps in
2004, you may recall the feeling.
Google Maps was among an emerging class of applications that took browser-based programming as
seriously as back-end programming and made us think differently about the application canvas provided
by the web browser. (Oddpost, which provided Outlook-style email functionality in a webmail client as
early as 2003, was another notable pioneer.) The proliferation of these applications and the increasing
market penetration of browsers that supported them led to a genuine renaissance in web application
engineering. “Web 2.0” was born, and Ajax became the “it” technology. The Web was suddenly interesting
all over again. JavaScript, as the only programming language of the Web, became more interesting, too.
Interesting, but hard to do well. JavaScript and its companion APIs in the Document Object Model (DOM)
and Browser Object Model (BOM) were inconsistently implemented, making cross-browser
implementations vastly more difficult than they needed to be. The profession of front-end engineering
was still young. University curricula had not (and still have not) stepped in to meet the training challenge.
JavaScript, arguably the most important programming language in the world by the end of 2004, was not
a first-class subject in the academic sense of the word. A new day was dawning on the Web, and there
was a serious question as to whether there would be enough knowledgeable, well-informed engineers to
meet the new challenges.
Many technical writers stepped in to fill the gap with books on JavaScript. There were dozens of these
over the years, but by and large they were a disappointing lot. Some of them promoted techniques that
flast.indd xxviiflast.indd xxvii 12/8/08 12:01:45 PM12/8/08 12:01:45 PM
xxviii
were relevant only in retrograde browsers; some promoted techniques that were easy to cut and paste
but hard to extend and maintain. Puzzlingly, many books on JavaScript seemed to be written by people
who didn’t really like JavaScript, who didn’t think you should like it, and who weren’t optimistic about

your ability to understand it fully.
One of the genuinely good books in the world of front-end engineering arrived when Nicholas C. Zakas
published the first edition of Professional JavaScript for Web Developers in 2005. At the time, my colleagues
and I were working at Yahoo! to create the Yahoo! User Interface Library (YUI) as a foundation for
front-end engineering here and to evangelize best practices in our nascent discipline. Every Friday, we’d
gather in a classroom to talk about the front-end engineering and to teach classes on JavaScript, CSS, and
the creation of web applications in the browser. We carefully reviewed the offerings at the time for books
that would help new engineers learn how to build robust, standards-based, easy-to-maintain web
applications using advanced JavaScript and DOM scripting. As soon as it was published, Zakas’s book
became our textbook for JavaScript.
We’ve been using it ever since. We thought so highly of the book that we talked Zakas into coming to
Yahoo! to help shape the front-end engineering community here.
What Zakas accomplished with Professional JavaScript for Web Developers is singular: He treated JavaScript
as a subject that is both serious and accessible. If you are a programmer, you will learn where JavaScript
fits into the broader spectrum of languages and paradigms with which you’re familiar. You’ll learn how
its system of inheritance and its intrinsic dynamism are, yes, unconventional but also liberating and
powerful. You’ll learn to appreciate JavaScript as a language from a fellow programmer who respects it
and understands it.
If you’re one of those liberal arts majors who was drawn into this profession in the boom years and never
left, and if you want to fill in the gaps of your understanding of JavaScript, you’ll find Zakas to be the
mentor you’ve always wanted — the one who will help you make the transition from “making things
work” to “making things that work well.” He’ll leave you with a serious understanding of a serious subject.
Best of all, you’ll find that he doesn’t pander to preconceived notions about how deeply you should
understand the language. He takes it seriously, and in a patient, accessible way he helps you to do the same.
This second edition of Professional JavaScript for Web Developers — expanded, updated, improved — drops
some subjects that are less relevant to the profession today and upgrades the rest with what we’ve
learned between 2005 and 2008. These years have been important ones, and Zakas is on the front line of
the process of learning. He’s spent those years architecting the current generation of the Web’s most
popular personal portal (My Yahoo!) and the next version of the web’s most visited site (Yahoo!’s front
page). Insights forged in these complex, ultra-high-volume applications inform every page of this new

volume, all passed through Zakas’s unique filter as a teacher/author.
As a result, his solutions go beyond being book-smart and include the kind of practical wisdom you can
only get by living and breathing code on a daily basis.
And that’s seriously good news for the rest of us. Professional JavaScript for Web Developers is now even
better, even more relevant, and even more important to have on your shelf.
Eric Miraglia, Ph.D.
Sr. Engineering Manager, Yahoo! User Interface Library (YUI)
Sunnyvale, California
F oreword
flast.indd xxviiiflast.indd xxviii 12/8/08 12:01:45 PM12/8/08 12:01:45 PM
Introduction
Some claim that JavaScript is now the most popular programming language in the world, running any
number of complex web applications that the world relies on to do business, make purchases, manage
processes, and more.
JavaScript is very loosely based on Java, an object - oriented programming language popularized for use on the
Web by way of embedded applets. Although JavaScript has a similar syntax and programming methodology,
it is not a “ light ” version of Java. Instead, JavaScript is its own dynamic language, finding its home in web
browsers around the world and enabling enhanced user interaction on web sites and web applications alike.
In this book, JavaScript is covered from its very beginning in the earliest Netscape browsers to the
present - day incarnations flush with support for the DOM and Ajax. You learn how to extend the
language to suit specific needs and how to create seamless client - server communication without
intermediaries such as Java or hidden frames. In short, you learn how to apply JavaScript solutions to
business problems faced by web developers everywhere.
What Does This Book Cover?
Professional JavaScript for Web Developers , 2nd Edition, provides a developer - level introduction along with
the more advanced and useful features of JavaScript.
Starting at the beginning, the book explores how JavaScript originated and evolved into what it is today.
A detailed discussion of the components that make up a JavaScript implementation follows, with specific
focus on standards such as ECMAScript and the Document Object Model (DOM). The differences in
JavaScript implementations used in different popular web browsers are also discussed.

Building on that base, the book moves on to cover basic concepts of JavaScript, including its version of
object - oriented programming, inheritance, and its use in various markup languages such as HTML. An
in - depth examination of events and event handling is followed by an exploration of browser-detection
techniques and a guide to using regular expressions in JavaScript. The book then takes all this
knowledge and applies it to creating dynamic user interfaces.
The last part of the book is focused on advanced topics, including performance and memory
optimization, best practices, and a look at where JavaScript is going in the future.
Who Is This Book For?
This book is aimed at the following three groups of readers:
Experienced developers familiar with object - oriented programming who are looking to learn
JavaScript as it relates to traditional object-oriented (OO) languages such as Java and C++
Web application developers attempting to enhance the usability of their web sites and web
applications
Novice JavaScript developers aiming to better understand the language



flast.indd xxixflast.indd xxix 12/8/08 12:01:45 PM12/8/08 12:01:45 PM
Introduction
xxx
In addition, familiarity with the following related technologies is a strong indicator that this book is for
you:
Java
PHP
ASP.NET
HTML
CSS
X M L
This book is not aimed at beginners who lack a basic computer-science background or those looking to
add some simple user interactions to web sites. These readers should instead refer to Wrox ’ s Beginning

JavaScript, 3rd Edition (Wiley, 2007).
What You Need to Use This Book
To run the samples in the book, you need the following:
Windows 2000, Windows Server 2003, Windows XP, Vista, or Mac OS X
Internet Explorer 6 or higher, Firefox 2 or higher, Opera 9 or higher, Chrome 0.2 or higher, or
Safari 2 or higher.
The complete source code for the samples is available for download at
www.wrox.com/ .
How This Book Is Structured
This book comprises the following chapters:
Chapter 1, What Is JavaScript? — Explains the origins of JavaScript: where it came from, how it
evolved, and what it is today. Concepts introduced include the relationship between JavaScript and
ECMAScript, the Document Object Model (DOM), and the Browser Object Model (BOM). A discussion
of the relevant standards from the European Computer Manufacturer ’ s Association (ECMA) and the
World Wide Web Consortium (W3C) is also included.
Chapter 2, JavaScript in HTML — Examines how JavaScript is used in conjunction with HTML to
create dynamic web pages. This chapter introduces the various ways of embedding JavaScript into a
page, including a discussion surrounding the JavaScript content - type and its relationship to the

< script > element.
Chapter 3, Language Basics — Introduces basic language concepts, including syntax and flow control
statements. This chapter explains the syntactic similarities of JavaScript and other C - based languages
and points out the differences. Type coercion is introduced as it relates to built - in operators.









flast.indd xxxflast.indd xxx 12/8/08 12:01:46 PM12/8/08 12:01:46 PM
Introduction
xxxi
Chapter 4, Variables, Scope, and Memory — Explores how variables are handled in JavaScript given
their loosely typed nature. A discussion about the differences between primitive and reference values
is included, as is information about execution context as it relates to variables. Also, a discussion about
garbage collection in JavaScript explains how memory is reclaimed when variables go out of scope.
Chapter 5, Reference Types — Covers all of the details regarding JavaScript ’ s built - in reference types,
such as
Object and Array . Each reference type described in ECMA - 262 is discussed both in theory
and how it relates to browser implementations.
Chapter 6, Object - Oriented Programming — Explains how to use object - oriented (OO) programming
in JavaScript. Since JavaScript has no concept of classes, several popular techniques are explored for
object creation and inheritance. Also covered in this chapter is the concept of function prototypes and
how that relates to an overall OO approach.
Chapter 7, Anonymous Functions — Explores one of the most powerful aspects of JavaScript:
anonymous functions. Topics include closures, how the
this object works, the module pattern, and
creating private object members.
Chapter 8, The Browser Object Model — Introduces the Browser Object Model (BOM), which is
responsible for objects allowing interaction with the browser itself. Each of the BOM objects is covered,
including
window , document , location , navigator , and screen .
Chapter 9, Client Detection — Explains various approaches to detecting the client machine and its
capabilities. Different techniques include capability detection and user - agent string detection. This
chapter discusses the pros and cons as well as the situational appropriateness of each approach.
Chapter 10, The Document Object Model — Introduces the Document Object Model (DOM) objects
available in JavaScript as defined in DOM Level 1. A brief introduction to XML and its relationship to
the DOM gives way to an in - depth exploration of the entire DOM and how it allows developers to

manipulate a page.
Chapter 11, DOM Levels 2 and 3 — Builds on the previous chapter, explaining how DOM Levels 2
and 3 augmented the DOM with additional properties, methods, and objects. Compatibility issues
between Internet Explorer and other browsers are discussed.
Chapter 12, Events — Explains the nature of events in JavaScript, where they originated, legacy
support, and how the DOM redefined how events should work. A variety of devices are covered,
including the Wii and iPhone.
Chapter 13, Scripting Forms — Looks at using JavaScript to enhance form interactions and work
around browser limitations. The discussions in this chapter focus on individual form elements such as
text boxes and select boxes and on data validation and manipulation.
Chapter 14, Error Handling and Debugging — Discusses how browsers handle errors in JavaScript
code and presents several ways to handle errors. Debugging tools and techniques are also discussed
for each browser, including recommendations for simplifying the debugging process.
Chapter 15, XML in JavaScript — Presents the features of JavaScript used to read and manipulate
eXtensible Markup Language (XML) data. This chapter explains the differences in support and objects in
various web browsers, and offers suggestions for easier cross - browser coding. This chapter also covers
the use of eXtensible Stylesheet Language Transformations (XSLT) to transform XML data on the client.
flast.indd xxxiflast.indd xxxi 12/8/08 12:01:46 PM12/8/08 12:01:46 PM
Introduction
xxxii
Chapter 16, ECMAScript for XML — Discusses the ECMAScript for XML (E4X) extension to
JavaScript, which is designed to simplify working with XML. This chapter explains the advantages of
E4X over using the DOM for XML manipulation.
Chapter 17, Ajax and JSON — Looks at common Ajax techniques, including the use of the

XMLHttpRequest object and Internet Explorer ’ s XDomainRequest object for cross - domain Ajax. This
chapter explains the differences in browser implementations and support as well as recommendations
for usage.
Chapter 18, Advanced Techniques — Dives into some of the more complex JavaScript patterns,
including function currying, partial function application, and dynamic functions. This chapter also

covers creating a custom event framework to enable simple event support for custom objects.
Chapter 19, Client - Side Storage — Discusses the various techniques for storing data on the client
machine. This chapter begins with a discussion of the most commonly supported feature, cookies, and
then discusses newer functionality such as DOM storage.
Chapter 20, Best Practices — Explores approaches to working with JavaScript in an enterprise
environment. Techniques for better maintainability are discussed, including coding techniques,
formatting, and general programming practices. Execution performance is discussed and several
techniques for speed optimization are introduced. Last, deployment issues are discussed, including
how to create a build process.
Chapter 21, Upcoming APIs — Introduces APIs being created to augment JavaScript in the browser.
Even though these APIs aren ’ t yet complete or fully implemented, they are on the horizon and
browsers have already begun partially implementing their features. This chapter includes discussions
on the Selectors API and HTML 5.
Chapter 22, The Evolution of JavaScript — Looks into the future of JavaScript to see where the
language is headed. ECMAScript 3.1, ECMAScript 4, and ECMAScript Harmony are discussed.
Conventions
To help you get the most from the text and keep track of what ’ s happening, a number of conventions are
used throughout this book.
Boxes like this one hold important, not - to - be forgotten information that is directly
relevant to the surrounding text.
Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles in the text:
N ew terms and important words are italicized when they’re introduced.
K eyboard combinations are shown like this: Ctrl+A.
F ile names, URLs, and code within the text look like this:
persistence.properties .



flast.indd xxxiiflast.indd xxxii 12/8/08 12:01:46 PM12/8/08 12:01:46 PM

Introduction
xxxiii
C ode is presented in two different ways:

Monofont type with no highlighting is used for most code examples.
Gray highlighting is used to emphasize code that’s particularly important in the
present context.
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually
or to use the source code files that accompany the book. All of the source code used in this book is
available for download at
www.wrox.com . Once at the site, simply locate the book ’ s title (either by using
the Search box or by using one of the title lists) and click the Download Code link on the book ’ s detail
page to obtain all the source code for the book.
Because many books have similar titles, you may find it easiest to search by ISBN. This book ’ s ISBN is
978 - 0 - 470 - 22780 - 0.
After you download the code, just decompress it with your favorite compression tool. Alternately, you
can go to the main Wrox code download page at
www.wrox.com/dynamic/books/download.aspx to
see the code available for this book and all other Wrox books.
Errata
We make every effort to ensure that there are no errors in the text or in the code. However, no one is
perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or
faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save
another reader hours of frustration and help us provide even higher - quality information.
To find the errata page for this book, go to
www.wrox.com and locate the title using the Search box or one
of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all
errata that has been submitted for this book and posted by Wrox editors. A complete book list, including
links to each book ’ s errata, is also available at

www.wrox.com/misc - pages/booklist.shtml .
If you don ’ t spot “ your ” error on the Book Errata page, go to
www.wrox.com/contact/techsupport
.shtml
and complete the form there to send us the error you have found. We ’ ll check the information and, if
appropriate, post a message to the book ’ s errata page and fix the problem in subsequent editions of the book.
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com . The forums are a web - based
system for you to post messages relating to Wrox books and related technologies, as well as to interact
with other readers and technology users. The forums offer a subscription feature to e - mail you topics of
interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry
experts, and your fellow readers are present on these forums.

flast.indd xxxiiiflast.indd xxxiii 12/8/08 12:01:46 PM12/8/08 12:01:46 PM
Introduction
xxxiv
At , you will find a number of different forums that will help you not only as you
read this book, but also as you develop your own applications. To join the forums, just follow these steps:
1. Go to p2p.wrox.com and click the Register link.
2. Read the terms of use and click Agree.
3. Complete the required information to join as well as any optional information you wish to
provide, and click Submit.
4. You will receive an e - mail with information describing how to verify your account and complete
the joining process.
You can read messages in the forums without joining P2P, but in order to post your own messages, you
must join.
Once you join, you can post new messages and respond to messages other users post. You can read
messages at any time on the Web. If you would like to have new messages from a particular forum
e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to

questions about how the forum software works as well as many common questions specific to P2P and
Wrox books. To read the FAQs, click the FAQ link on any P2P page.
flast.indd xxxivflast.indd xxxiv 12/8/08 12:01:47 PM12/8/08 12:01:47 PM
Professional
JavaScript
®
for Web Developers
2nd Edition
flast.indd xxxvflast.indd xxxv 12/8/08 12:01:47 PM12/8/08 12:01:47 PM
What Is JavaScript?
When JavaScript first appeared in 1995, its main purpose was to handle some of the input
validation that had previously been left to server - side languages such as Perl. Prior to that time, a
round - trip to the server was needed to determine if a required field had been left blank or an
entered value was invalid. Netscape Navigator sought to change that with the introduction of
JavaScript. The capability to handle some basic validation on the client was an exciting new feature
at a time when use of telephone modems was widespread. The associated slow speeds turned
every trip to the server into an exercise in patience.
Since that time, JavaScript has grown into an important feature of every major web browser on the
market. No longer bound to simple data validation, JavaScript now interacts with nearly all
aspects of the browser window and its contents. JavaScript is recognized as a full programming
language, capable of complex calculations and interactions, including closures, anonymous
(lambda) functions, and even metaprogramming. JavaScript has become such an important part of
the Web that even alternative browsers, including those on mobile phones and those designed for
users with disabilities, support it. Even Microsoft, with its own client - side scripting language
called VBScript, ended up including its own JavaScript implementation in Internet Explorer from
its earliest version.
The rise of JavaScript from a simple input validator to a powerful programming language could
not have been predicted. JavaScript is at once a very simple and very complicated language that
takes minutes to learn but years to master. To begin down the path to using JavaScript ’ s full
potential, it is important to understand its nature, history, and limitations.

A Short History
Around 1992, a company called Nombas (later bought by Openwave) began developing an
embedded scripting language called C - minus - minus (Cmm for short). The idea behind Cmm was
simple: a scripting language powerful enough to replace macros, but still similar enough to C (and
C++) that developers could learn it quickly. This scripting language was packaged in a shareware
product called CEnvi, which first exposed the power of such languages to developers. Nombas
c01.indd 1c01.indd 1 12/8/08 11:21:48 AM12/8/08 11:21:48 AM
Chapter 1: What Is JavaScript?
2
eventually changed the name Cmm to ScriptEase. ScriptEase became the driving force behind Nombas
products. When the popularity of Netscape Navigator started peaking, Nombas developed a version of
CEnvi that could be embedded into web pages. These early experiments were called Espresso Pages , and
they represented the first client - side scripting language used on the World Wide Web. Little did Nombas
know that its ideas would become an important foundation for the Internet.
As the Web gained popularity, a gradual demand for client - side scripting languages developed. At
the time, most Internet users were connecting over a 28.8 kbps modem even though web pages were
growing in size and complexity. Adding to users ’ pain was the large number of round - trips to the server
required for simple form validation. Imagine filling out a form, clicking the Submit button, waiting
30 seconds for processing, and then being met with a message indicating that you forgot to complete a
required field. Netscape, at that time on the cutting edge of technological innovation, began seriously
considering the development of a client - side scripting language to handle simple processing.
Brendan Eich, who worked for Netscape at the time, began developing a scripting language called
LiveScript for the release of Netscape Navigator 2 in 1995, with the intention of using it both in the
browser and on the server (where it was to be called LiveWire). Netscape entered into a development
alliance with Sun Microsystems to complete the implementation of LiveScript in time for release. Just
before Netscape Navigator 2 was officially released, Netscape changed LiveScript ’ s name to JavaScript to
capitalize on the buzz that Java was receiving from the press.
Because JavaScript 1.0 was such a hit, Netscape released version 1.1 in Netscape Navigator 3. The
popularity of the fledgling Web was reaching new heights and Netscape had positioned itself to be
the leading company in the market. At this time, Microsoft decided to put more resources into a

competing browser named Internet Explorer. Shortly after Netscape Navigator 3 was released, Microsoft
introduced Internet Explorer 3 with a JavaScript implementation called JScript (so called to avoid any
possible licensing issues with Netscape). This major step for Microsoft into the realm of web browsers in
August 1996 is now a date that lives in infamy for Netscape, but it also represented a major step forward
in the development of JavaScript as a language.
Microsoft ’ s implementation of JavaScript meant that there were three different JavaScript versions
floating around: JavaScript in Netscape Navigator, JScript in Internet Explorer, and CEnvi in ScriptEase.
Unlike C and many other programming languages, JavaScript had no standards governing its syntax or
features, and the three different versions only highlighted this problem. With industry fears mounting, it
was decided that the language must be standardized.
In 1997, JavaScript 1.1 was submitted to the European Computer Manufacturers Association
(Ecma) as a proposal. Technical Committee #39 (TC39) was assigned to “ standardize the syntax
and semantics of a general purpose, cross - platform, vendor - neutral scripting language ”
(
a - international.org/memento/TC39.htm ). Made up of programmers from
Netscape, Sun, Microsoft, Borland, and other companies with interest in the future of scripting, TC39
met for months to hammer out ECMA - 262, a standard defining a new scripting language named
ECMAScript.
The following year, the International Organization for Standardization and International Electrotechnical
Commission (ISO/IEC) also adopted ECMAScript as a standard (ISO/IEC - 16262). Since that time,
browsers have tried, with varying degrees of success, to use ECMAScript as a basis for their JavaScript
implementations.
c01.indd 2c01.indd 2 12/8/08 11:21:49 AM12/8/08 11:21:49 AM

×