Вы находитесь на странице: 1из 1098
Activate Your Web Pages The Definitive Guide O’REILLY® David Flanagan 9 Web Programming/JavaScript JavaScript: The Definitive Guide This book is a programmer's guide and comprehensive reference to the core JavaScript language and to the client-side JavaScript APIs defined by web browsers, The sixth edition covers HTMIS and E¢ 2MAScript 5. Many chapters have been completely rewritten to bring them in line with toda best web development practices New chapters in this edition document jQuery and server side JavaScript Recommended for experienced programmers who want to learn the programming language of the Web, and for current JavaScript programmers who want to master it David Flanagan is also the author of The Ruby Programming Language, Java ina Nutshell, ancl JavaScript Pocket Reference. Previous programming experience is recommended. The Essential JavaScript Reference Since 1996, JavaScript: The Definitive Guide has been the bible for JavaScript programmers. With more than 500,000 copies in print, web develope re still raving about it “Amust-have reference for expert JavaScript programmers...well-organized and detailed.” —Brendan ich creator of avaScrpt, TO of Mozilla “Imade a career of what | learned from JavaScript: The Definitive Guide.” —Andrew Hedges Tapulous “The Definitive Guide taught me JavaScript.” —Tom Robinson cofounder of280 North, creator of Cappuccino “Iknow which parts of JavaScript matter, based on how crinkled the spine of my copy of The Definitive Guide is in that section.” —1.Chris Anderson cofounder of CouchBase, Apache CouchDB committer, and author of CouchOB: The Definitive Guide *,,an indispensable reference for all JavaScript developers. If there’s something I need to know about JavaScript, I trust The Definitive Guide will have the right answer for me. It's that good.” —Rey Bango Microsoft Client-Web Community Program Manager and Query Team member Us $49.99 CAN $57.99, ISBN: 978-0-596-80552-4 5499 (NINA) 0) ai Twitter: @oreillymedia facebook.com/oreilly O'REILLY” oreilly.com Download from Wow! eBook JavaScript: The Definitive Guide SIXTH EDITION JavaScript: The Definitive Guide David Flanagan O'REILLY” Beijing + Cambridge « Farnham + Kéln + Sebastopol + Tokyo JavaScript: The Definitive Guide, Sixth Edition by Davie Flanagan Copyright ©2011 Davie Flanagan. All rights ceservee Printec in the Unitee States of America Publishce by O'Reilly 1Accia, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 OReilly books may be purchasec for ecucational, business, or sales promotional use. Online ecitions are also available for most titles (http:/my safariboo online com). For mote iniormation, contact our corporate/institutional sales cepartment: (800) 998-9938 or corporate@orcilly com Editor: 1ike Loukices Indexer: Ellen Troutman Zaig Production Editor: Teresa Elscy Cover Designer: Karen Montgomery Proofreader: Teresa Elsey Interior Designer: Davic Furato Ilustrator: Robert Romano Printing History: ‘August 1996: Beta Ecition. January 1997: Sccone Ecition June 1998: Thire Ecition Jnuary 2002. Fourth Ecition ‘August 2006 Fifth Ecition March 2011 Sixth Ecition Nutshell Hancbook, the Nutshell tancbook logo, anc the O'Reilly logo arc vegisteree trademarks of OReilly Mecia, In. JavaScript: The Definitive Guide, the image of a Javan chinoceros, anc relatec trace ress are teacemarks of O'Reilly Mdecia, Ine Many of the éesignations uscé by manufacturers ané sellers to cistinguish their procucts are claimec as tracemarks. Where those cesignations appear in this book, anc O'Reilly lecia, Inc., was aware of a tracemark elaim, the cesignations have been printec in caps oc initial caps. While every precaution has been taken inthe preparation oj this book, the publisher ane authors assume no responsibility for errors o¢ omissions, or for camages cesulting from the use of the information con. tainec herein ISBN: 978.0-596-80552-4 Ist 1302719886 This book is dedicated to all who teach peace and resist violence. Table of Contents Preface ......... 1. Introduction to JavaScript .......... 11 Core JavaScript 12 Client-Side JavaScript 8 Partl. Core JavaScript 2. Lexical Structure ... 2.1 Character Set 2.2 Comments 23 Literals Identitiers and Reserved Words 5 Optional Semicolons seeeeeeeeee 3. Types, Values, and Variables ............ 3.1 Numbers 3.2 Text 3.3 Boolean Values 34 oulland undeéined 3.5 The Global Object 3.6 Wrapper Objects 3.7 Immutable Primitive Valucs and Mutable Object Reicrences 3.8 Type Conversions 5 3.9 Variable Declaration 32 3.10 Variable Scope 353 4, Expressions and Operators .........ccseccceessseeecessecesessseeeseesseee 57 4.1 Primary Expressions 37 4.2 Object and Array Initializers 58 4.3 Function Detinition Expressions, 59 vi 44 Property Access Expressions 4.5 Invocation Expressions 4.6 Object Creation Expressions, 4.7 Operator Overview 4.8 Arithmetic Expressions 4.9 Relational Expressions 4.10 Logical Expressions 4.11 Assignment Expressions 4.12 Evaluation Expressions 4.13 Miscellancous Operators 5. Statements seeeeeeeee seeeeeeeee seeeeeeee. + 87 5.1 Expression Statements 88 Compound and Empty Statements 88 5.3 Declaration Statements 89 54 Conditionals 2 5.5 Loops 97 5.6 Jumps 102 57 Misccllancous Statements 108 5.8 Summary of JavaScript Statements 42 6. Objects ..... saeeeeeeeeeee 115 6.1 Creating Objects lle 62 Querying and Setting Properties 120 6.3 Deleting Properties 124 64 Testing Propertics 125 6.5 Enumerating Properties 126 6.6 Property Gettcrs and Setters 128 67 Property Attributes 131 68 Object Attributes 135 69 Sctializing Objects 138 6.10 Object Methods 138 Te AMAYS .oeeeeeseesteeeteeene 1 71 Creating Acrays 141 Reading and Writing Array Elements 142 3 Sparse Artays 144 4 Actay Length 144 5 Adding and Deleting Array Elements 145 6 Itcrating Arrays 146 7 Multidimensional Arrays 148 7.8 Artay Methods 148 7.9 ECMAScript 5 Attay Methods 153 7.10 Actay Type 157 viii | Table of Contents TAL Actay-Like Objects 158 7.12 Strings As Accays 160 8. Functions ......... sesee cece ees 163 8.1 Deéining Functions Led 82 Invoking Functions 166 8.3 Function Arguments and Parameters 171 84 Functions As Values 176 8.5 Functions As Namespaces 178 8.6 Closures 180 8.7 Function Propertics, Methods, and Constructor 186 8.8 Functional Progeamming 191 9. Classes and Modules ............... se neeeceee senses 199 9.1 Classes and Prototypes 200 9.2. Classes and Constructors 201 9.3 JavaStyle Classes in JavaScript 205 9.4 Augmenting Classes 208 9.5 Classes and Types 209 9.6 Object-Oriented Techniques in JavaScript 215 9.7 Subclasses 228 9.8 Classes in ECMAScript 5 238 9.9 Modules 246 10. Pattern Matching with Regular Expressions ........ 10.1 Deiining Regular Expressions 10.2 String Methods éor Pattern Matching, 10.3 The RegExp Object 11. JavaScript Subsets and Extensions ......... 11.1 JavaScript Subsets 11.2 Constants and Scoped Variables 11.3 Destructuring Assign ment 114 Iteration 11.5 Shorthand Functions 11.6 Multiple Catch Clauses 1.7 E4X: ECMAScript for XML 12. Server-Side JavaScript .... 12.1 Scripting Java with Rhino 12.2 Asynchconous I/O with Node Table ofContents | ix Part ll. Client-Side JavaScript 13. JavaScript in Web Browsers ... 13.1 Client-Side JavaScript 13.2 Embedding JavaScript in HTML 13.3 Execution of JavaScript Programs 13.4 Compatibility and Interoperability 13.5 Accessibility 13.6 Security 13.7 Client-Side Frameworks 14. The Window Object .. 14.1 Timers 14.2 Browsct Location and Navigation 14.3 Browsing History 14.4 Browscr and Screen Inéormation 14.5 Dialog Boxes 14.6 Error Handling 14.7 Document Elements As Window Properties 14.8 Multiple Windows and Frames 15. Scripting Documents . 15.1 Overview of the DOM 152 Selecting Document Elements 15.3 Document Structure and Traversal 154 Attcibutes 15.5 Element Content 15.6 Creating, Inserting, and Deleting Nodes 15.7 Example: Generating a Table o¢ Contents 15.8 Document and Element Geometry and Scrolling 15.9 HTML Forms 15.10 Other Document Ecatures 16. Scripting (SS .........605 a3 16.1 Overview of CSS 414 16.2 Important CSS Properties 419 16.3 Scripting Inline Styles 431 164 Querying Computed Styles 435 16.5 Scripting CSS Classes 437 16.6 Scripting Stylesheets 440 17. Handling Events .........-...06+ 17.1 Types of Events x | Table of Contents 18. 19. 20. 21. 22. Registering Event Handlers 456 Event Handler Invocation 460 Document Load Events 465 Mouse Events 467 Mousewheel Events 471 Drag and Drop Events 474 Text Events 481 7.9 Keyboard Events 484 Scripted HTTP .........2.0eeeee 18.1 Using XMLHttpRequest 182 HTTP by