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

483 professional javascript for web developers, 3rd edition

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 (46.88 MB, 964 trang )

www.it-ebooks.info


www.it-ebooks.info
ffirs.indd iv

12/8/11 12:54:54 PM


PROFESSIONAL
JAVASCRIPT® FOR WEB DEVELOPERS
FOREWORD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii
CHAPTER 1

What Is JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

CHAPTER 2

JavaScript in HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13

CHAPTER 3

Language Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

CHAPTER 4

Variables, Scope, and Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

CHAPTER 5


Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

CHAPTER 6

Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

CHAPTER 7

Function Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

CHAPTER 8

The Browser Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

CHAPTER 9

Client Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

CHAPTER 10

The Document Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309

CHAPTER 11

DOM Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

CHAPTER 12

DOM Levels 2 and 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381


CHAPTER 13

Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431

CHAPTER 14

Scripting Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511

CHAPTER 15

Graphics with Canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551

CHAPTER 16

HTML5 Scripting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591

CHAPTER 17

Error Handling and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607

CHAPTER 18

XML in JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641

CHAPTER 19

ECMAScript for XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671

CHAPTER 20


JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691

CHAPTER 21

Ajax and Comet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701

CHAPTER 22

Advanced Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731

CHAPTER 23

Offline Applications and Client-Side Storage . . . . . . . . . . . . . . . . . . . . . 765

CHAPTER 24

Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801
Continues
www.it-ebooks.info

ffirs.indd i

12/8/11 12:54:52 PM


CHAPTER 25

Emerging APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835

APPENDIX A


ECMAScript Harmony . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857

APPENDIX B

Strict Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877

APPENDIX C

JavaScript Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885

APPENDIX D

JavaScript Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897

www.it-ebooks.info
ffirs.indd ii

12/8/11 12:54:54 PM


PROFESSIONAL

JavaScript® for Web Developers

www.it-ebooks.info
ffirs.indd iii


12/8/11 12:54:54 PM


www.it-ebooks.info
ffirs.indd iv

12/8/11 12:54:54 PM


PROFESSIONAL

JavaScript® for Web Developers
Third Edition

Nicholas C. Zakas

John Wiley & Sons, Inc.

www.it-ebooks.info
ffirs.indd v

12/8/11 12:54:54 PM


Professional JavaScript® for Web Developers, Third Edition
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256


www.wiley.com
Copyright © 2012 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-02669-4
ISBN: 978-1-118-22219-5 (ebk)
ISBN: 978-1-118-23309-2 (ebk)
ISBN: 978-1-118-26080-7 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
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.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with
standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media

such as a CD or DVD that is not included in the version you purchased, you may download this material at
. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2011943911
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 affi liates, in the United States and other
countries, and may not be used without written permission. JavaScript is a registered trademark of Oracle America, Inc.
All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any
product or vendor mentioned in this book.

www.it-ebooks.info
ffirs.indd vi

12/8/11 12:54:56 PM


To my parents, who never cease to support and inspire me.

www.it-ebooks.info
ffirs.indd vii

12/8/11 12:54:56 PM


www.it-ebooks.info
ffirs.indd viii

12/8/11 12:54:56 PM


ABOUT THE AUTHOR


NICHOLAS C. ZAKAS has been working with the web for over a decade. During that

time, he has worked both on corporate intranet applications used by some of the
largest companies in the world and on large-scale consumer websites such as My
Yahoo! and the Yahoo! homepage. As a presentation architect at Yahoo!, Nicholas
guided front-end development and standards for some of the most-visited websites in
the world. Nicholas is an established speaker and regularly gives talks at companies,
conferences, and meetups regarding front-end best practices and new technology.
He has authored several books, including Professional Ajax and High Performance JavaScript,
and writes regularly on his blog at Nicholas’s Twitter handle is
@slicknet.

ABOUT THE TECHNICAL EDITOR

JOHN PELOQUIN is a front-end engineer with over ten years of JavaScript experience ranging across

applications of all sizes. John earned his B.A. in mathematics from the University of California at
Berkeley and is currently a lead developer for a health care startup where he makes use of the latest
in front-end technologies. Prior to editing this volume, John edited JavaScript 24-Hour Trainer
by Jeremy McPeak (Wiley, 2010). When he is not coding or collecting errata, John is often found
engaged in mathematics, philosophy, or juggling.

www.it-ebooks.info
ffirs.indd ix

12/8/11 12:54:57 PM


www.it-ebooks.info

ffirs.indd x

12/8/11 12:54:57 PM


CREDITS

EXECUTIVE EDITOR

PRODUCTION MANAGER

Carol Long

Tim Tate

SENIOR PROJECT EDITOR

VICE PRESIDENT AND EXECUTIVE GROUP
PUBLISHER

Kevin Kent

Richard Swadley
TECHNICAL EDITOR

John Peloquin

VICE PRESIDENT AND EXECUTIVE
PUBLISHER


PRODUCTION EDITOR

Neil Edde

Kathleen Wisor
ASSOCIATE PUBLISHER
COPY EDITOR

Jim Minatel

Katherine Burt

PROJECT COORDINATOR, COVER

EDITORIAL MANAGER

Katie Crocker

Mary Beth Wakefield
FREELANCER EDITORIAL MANAGER

Rosemarie Graham
ASSOCIATE DIRECTOR OF MARKETING

David Mayhew

PROOFREADER

Nicole Hirschman
INDEXER


Robert Swanson

MARKETING MANAGER

COVER DESIGNER

Ashley Zurcher

LeAndra Young

BUSINESS MANAGER

COVER IMAGE

Amy Knies

© iStock/Andrew Rich

www.it-ebooks.info
ffirs.indd xi

12/8/11 12:54:57 PM


www.it-ebooks.info
ffirs.indd xii

12/8/11 12:54:58 PM



ACKNOWLEDGMENTS

EVEN THOUGH THE AUTHOR’S NAME is the one that graces the cover of a book, no book is the result

of one person’s efforts, and I’d like to thank a few of the people involved in this one.
First and foremost, thanks to John Wiley & Sons for continuing to give me opportunities to write.
They were the only people willing to take a risk on an unknown author for the fi rst edition of
Professional JavaScript for Web Developers, and for that I will be forever grateful.
Thanks to the staff of John Wiley & Sons, specifically Kevin Kent and John Peloquin, who both
did an excellent job keeping me honest and dealing with my frequent changes to the book as I
was writing.
I’d also like to thank everyone who provided feedback on draft chapters of the book: Rob Friesel,
Sergey Ilinsky, Dan Kielp, Peter-Paul Koch, Jeremy McPeak, Alex Petrescu, Dmitry Soshnikov, and
Juriy “Kangax” Zaytsev. Your feedback made this book something that I’m extremely proud of.
A special thanks to Brendan Eich for his corrections to the history of JavaScript included in Chapter 1.
Last, but certainly not least, thanks to Rey Bango for writing the foreword of this book. I had the
pleasure of meeting Rey for the fi rst time in 2010 after conversing online for several years. He’s one
of the truly nice guys in the industry, and I’m honored that he agreed to lend his time to this book.

www.it-ebooks.info
ffirs.indd xiii

12/8/11 12:54:58 PM


www.it-ebooks.info
ffirs.indd xiv

12/8/11 12:54:58 PM



CONTENTS

FOREWORD

xxxi

INTRODUCTION

xxxiii

CHAPTER 1: WHAT IS JAVASCRIPT?

A Short History
JavaScript Implementations

1

2
3

ECMAScript
The Document Object Model (DOM)
The Browser Object Model (BOM)

JavaScript Versions
Summary

3

6
9

10
11

CHAPTER 2: JAVASCRIPT IN HTML

The <script> Element

13

13

Tag Placement
Deferred Scripts
Asynchronous Scripts
Changes in XHTML
Deprecated Syntax

16
16
17
18
20

Inline Code versus External Files
Document Modes
The <noscript> Element
Summary

CHAPTER 3: LANGUAGE BASICS

Syntax

20
20
22
22
25

25

Case-sensitivity
Identifiers
Comments
Strict Mode
Statements

25
26
26
27
27

Keywords and Reserved Words
Variables
Data Types
The typeof Operator

28

29
31
31

www.it-ebooks.info
ftoc.indd xv

12/8/11 12:56:22 PM


CONTENTS

The Undefined Type
The Null Type
The Boolean Type
The Number Type
The String Type
The Object Type

32
33
34
35
41
44

Operators

45


Unary Operators
Bitwise Operators
Boolean Operators
Multiplicative Operators
Additive Operators
Relational Operators
Equality Operators
Conditional Operator
Assignment Operators
Comma Operator

46
49
56
59
61
63
65
67
67
68

Statements

69

The if Statement
The do-while Statement
The while Statement
The for Statement

The for-in Statement
Labeled Statements
The break and continue Statements
The with Statement
The switch Statement

Functions

69
70
70
71
72
73
73
75
76

78

Understanding Arguments
No Overloading

Summary

80
83

83


CHAPTER 4: VARIABLES, SCOPE, AND MEMORY

Primitive and Reference Values
Dynamic Properties
Copying Values
Argument Passing
Determining Type

85

85
86
86
88
89

Execution Context and Scope

90

Scope Chain Augmentation
No Block-Level Scopes

92
93

xvi

www.it-ebooks.info
ftoc.indd xvi


12/8/11 12:56:23 PM


CONTENTS

Garbage Collection

96

Mark-and-Sweep
Reference Counting
Performance
Managing Memory

96
97
98
99

Summary

100

CHAPTER 5: REFERENCE TYPES

The Object Type
The Array Type

104

106

Detecting Arrays
Conversion Methods
Stack Methods
Queue Methods
Reordering Methods
Manipulation Methods
Location Methods
Iterative Methods
Reduction Methods

Download from Wow! eBook <www.wowebook.com>

103

110
110
112
113
114
116
118
119
121

The Date Type

122


Inherited Methods
Date-Formatting Methods
Date/Time Component Methods

The RegExp Type

124
125
126

128

RegExp Instance Properties
RegExp Instance Methods
RegExp Constructor Properties
Pattern Limitations

The Function Type

131
132
134
136

136

No Overloading (Revisited)
Function Declarations versus Function Expressions
Functions as Values
Function Internals

Function Properties and Methods

Primitive Wrapper Types

138
138
139
141
143

146

The Boolean Type
The Number Type
The String Type

148
149
151

Singleton Built-in Objects

161

The Global Object
The Math Object

162
166


Summary

170
xvii

www.it-ebooks.info
ftoc.indd xvii

12/8/11 12:56:23 PM


CONTENTS

CHAPTER 6: OBJECT-ORIENTED PROGRAMMING

Understanding Objects

173

173

Types of Properties
Defining Multiple Properties
Reading Property Attributes

Object Creation

174
178
179


180

The Factory Pattern
The Constructor Pattern
The Prototype Pattern
Combination Constructor/Prototype Pattern
Dynamic Prototype Pattern
Parasitic Constructor Pattern
Durable Constructor Pattern

Inheritance

180
181
184
197
198
199
200

201

Prototype Chaining
Constructor Stealing
Combination Inheritance
Prototypal Inheritance
Parasitic Inheritance
Parasitic Combination Inheritance


Summary

202
207
209
210
211
212

215

CHAPTER 7: FUNCTION EXPRESSIONS

Recursion
Closures

217

220
221

Closures and Variables
The this Object
Memory Leaks

224
225
227

Mimicking Block Scope

Private Variables

228
231

Static Private Variables
The Module Pattern
The Module-Augmentation Pattern

Summary

232
234
236

237

CHAPTER 8: THE BROWSER OBJECT MODEL

The window Object

239

239

The Global Scope
Window Relationships and Frames
Window Position

240

241
244

xviii

www.it-ebooks.info
ftoc.indd xviii

12/8/11 12:56:23 PM


CONTENTS

Window Size
Navigating and Opening Windows
Intervals and Timeouts
System Dialogs

The location Object

245
247
251
253

255

Query String Arguments
Manipulating the Location


256
257

The Navigator Object

259

Detecting Plug-ins
Registering Handlers

262
264

The screen Object
The history Object
Summary

265
267
268

CHAPTER 9: CLIENT DETECTION

Capability Detection

271

271

Safer Capability Detection

Capability Detection Is Not Browser Detection

Quirks Detection
User-Agent Detection

273
274

275
276

History
Working with User-Agent Detection
The Complete Script
Usage

Summary

277
286
303
306

306

CHAPTER 10: THE DOCUMENT OBJECT MODEL

Hierarchy of Nodes

309


310

The Node Type
The Document Type
The Element Type
The Text Type
The Comment Type
The CDATASection Type
The DocumentType Type
The DocumentFragment Type
The Attr Type

Working with the DOM

310
316
326
337
341
342
343
344
345

346

Dynamic Scripts
Dynamic Styles


346
348

xix

www.it-ebooks.info
ftoc.indd xix

12/8/11 12:56:24 PM


CONTENTS

Manipulating Tables
Using NodeLists

350
353

Summary

354

CHAPTER 11: DOM EXTENSIONS

Selectors API

357

357


The querySelector() Method
The querySelectorAll() Method
The matchesSelector() Method

Element Traversal
HTML5

358
358
359

360
361

Class-Related Additions
Focus Management
Changes to HTMLDocument
Character Set Properties
Custom Data Attributes
Markup Insertion
The scrollIntoView() Method

361
364
364
366
366
367
372


Proprietary Extensions

372

Document Mode
The children Property
The contains() Method
Markup Insertion
Scrolling

373
374
374
376
379

Summary

379

CHAPTER 12: DOM LEVELS 2 AND 3

DOM Changes

381

382

XML Namespaces

Other Changes

382
386

Styles

390

Accessing Element Styles
Working with Style Sheets
Element Dimensions

Traversals

391
396
401

408

NodeIterator
TreeWalker

410
413

Ranges

415


Ranges in the DOM
Ranges in Internet Explorer 8 and Earlier

Summary

415
424

428

xx

www.it-ebooks.info
ftoc.indd xx

12/8/11 12:56:24 PM


CONTENTS

CHAPTER 13: EVENTS

431

Event Flow

432

Event Bubbling

Event Capturing
DOM Event Flow

432
433
433

Event Handlers

434

HTML Event Handlers
DOM Level 0 Event Handlers
DOM Level 2 Event Handlers
Internet Explorer Event Handlers
Cross-Browser Event Handlers

The Event Object

434
437
438
439
441

442

The DOM Event Object
The Internet Explorer Event Object
Cross-Browser Event Object


Event Types

442
447
449

451

UI Events
Focus Events
Mouse and Wheel Events
Keyboard and Text Events
Composition Events
Mutation Events
HTML5 Events
Device Events
Touch and Gesture Events

452
458
459
471
478
479
482
490
494

Memory and Performance


498

Event Delegation
Removing Event Handlers

498
500

Simulating Events

502

DOM Event Simulation
Internet Explorer Event Simulation

Summary

502
508

509

CHAPTER 14: SCRIPTING FORMS

Form Basics

511

511


Submitting Forms
Resetting Forms
Form Fields

512
513
514

Scripting Text Boxes

520

Text Selection

521

xxi

www.it-ebooks.info
ftoc.indd xxi

12/8/11 12:56:25 PM


CONTENTS

Input Filtering
Automatic Tab Forward
HTML5 Constraint Validation API


Scripting Select Boxes

524
528
530

534

Options Selection
Adding Options
Removing Options
Moving and Reordering Options

Form Serialization
Rich Text Editing

536
537
538
539

540
542

Using contenteditable
Interacting with Rich Text
Rich Text Selections
Rich Text in Forms


543
543
547
549

Summary

549

CHAPTER 15: GRAPHICS WITH CANVAS

Basic Usage
The 2D Context

551

551
553

Fills and Strokes
Drawing Rectangles
Drawing Paths
Drawing Text
Transformations
Drawing Images
Shadows
Gradients
Patterns
Working with Image Data
Compositing


553
553
556
557
559
563
564
565
567
567
569

WebGL

571

Typed Arrays
The WebGL Context
Support

571
576
588

Summary

588

CHAPTER 16: HTML5 SCRIPTING


591

Cross-Document Messaging
Native Drag and Drop

591
593

Drag-and-Drop Events

593

xxii

www.it-ebooks.info
ftoc.indd xxii

12/8/11 12:56:25 PM


CONTENTS

Custom Drop Targets
The dataTransfer Object
DropEffect and effectAllowed
Draggability
Additional Members

Media Elements


594
595
596
597
598

598

Properties
Events
Custom Media Players
Codec Support Detection
The Audio Type

599
601
602
603
604

History State Management
Summary

605
606

CHAPTER 17: ERROR HANDLING AND DEBUGGING

Browser Error Reporting


607

607

Internet Explorer
Firefox
Safari
Opera
Chrome

608
609
610
612
613

Error Handling

614

The try-catch Statement
Throwing Errors
The error Event
Error-handling Strategies
Identify Where Errors Might Occur
Distinguishing between Fatal and Nonfatal Errors
Log Errors to the Server

Debugging Techniques


615
619
622
623
623
628
629

630

Logging Messages to a Console
Logging Messages to the Page
Throwing Errors

631
633
634

Common Internet Explorer Errors

635

Operation Aborted
Invalid Character
Member Not Found
Unknown Runtime Error
Syntax Error
The System Cannot Locate the Resource Specified


Summary

635
637
637
638
638
639

639
xxiii

www.it-ebooks.info
ftoc.indd xxiii

12/8/11 12:56:25 PM


×