Statistics
16
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-08

AuthorDavid Flanagan

JavaScript is the programming language of the web and is used by more software developers today than any other programming language. For nearly 25 years this best seller has been the go-to guide for JavaScript programmers. The seventh edition is fully updated to cover the 2020 version of JavaScript, and new chapters cover classes, modules, iterators, generators, Promises, async/await, and metaprogramming. You’ll find illuminating and engaging example code throughout. This book is for programmers who want to learn JavaScript and for web developers who want to take their understanding and mastery to the next level. It begins by explaining the JavaScript language itself, in detail, from the bottom up. It then builds on that foundation to cover the web platform and Node.js. Topics include: • Types, values, variables, expressions, operators, statements, objects, and arrays • Functions, classes, modules, iterators, generators, Promises, and async/await • JavaScript’s standard library: data structures, regular expressions, JSON, i18n, etc. • The web platform: documents, components, graphics, networking, storage, and threads • Node.js: buffers, files, streams, threads, child processes, web clients, and web servers • Tools and language extensions that professional JavaScript developers rely on

Tags
No tags
ISBN: 1491952008
Publisher: O'Reilly Media, Inc.
Publish Year: 2020
Language: 英文
Pages: 707
File Format: PDF
File Size: 17.1 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Seventh Edition JavaScript The Definitive Guide Master the World's Most-Used Programming Language David Flanagan
(This page has no text content)
Praise for JavaScript: The Definitive Guide, Seventh Edition “This book is everything you never knew you wanted to know about JavaScript. Take your JavaScript code quality and productivity to the next level. David’s knowledge of the language, its intricacies and gotchas, is astounding, and it shines through in this truly definitive guide to the JavaScript language.” —Schalk Neethling, Senior Frontend Engineer at MDN Web Docs “David Flanagan takes readers on a guided tour of JavaScript that will provide them with a feature-complete picture of the language and its ecosystem.” —Sarah Wachs, Frontend Developer and Women Who Code Berlin Lead “Any developer interested in being productive in codebases developed throughout JavaScript’s lifetime (including the latest and emerging features) will be well served by a deep and reflective journey through this comprehensive and definitive book.” —Brian Sletten, President of Bosatsu Consulting
(This page has no text content)
David Flanagan JavaScript: The Definitive Guide Master the World’s Most-Used Programming Language SEVENTH EDITION Boston Farnham Sebastopol TokyoBeijing
978-1-491-95202-3 [LSI] JavaScript: The Definitive Guide, Seventh Edition by David Flanagan Copyright © 2020 David Flanagan. All rights reserved. Printed in the United States of America. 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://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Jennifer Pollock Development Editor: Angela Rufino Production Editor: Deborah Baker Copyeditor: Holly Bauer Forsyth Proofreader: Piper Editorial, LLC Indexer: Judith McConville Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest June 1998: Third Edition November 2001: Fourth Edition August 2006: Fifth Edition May 2011: Sixth Edition May 2020: Seventh Edition Revision History for the Seventh Edition 2020-05-13: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491952023 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. JavaScript: The Definitive Guide, Sev‐ enth Edition, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
To my parents, Donna and Matt, with love and gratitude.
(This page has no text content)
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Introduction to JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Exploring JavaScript 3 1.2 Hello World 5 1.3 A Tour of JavaScript 5 1.4 Example: Character Frequency Histograms 11 1.5 Summary 14 2. Lexical Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.1 The Text of a JavaScript Program 15 2.2 Comments 16 2.3 Literals 16 2.4 Identifiers and Reserved Words 16 2.5 Unicode 17 2.6 Optional Semicolons 19 2.7 Summary 21 3. Types, Values, and Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.1 Overview and Definitions 23 3.2 Numbers 25 3.3 Text 32 3.4 Boolean Values 38 3.5 null and undefined 40 3.6 Symbols 41 3.7 The Global Object 42 3.8 Immutable Primitive Values and Mutable Object References 43 3.9 Type Conversions 45 vii
3.10 Variable Declaration and Assignment 53 3.11 Summary 60 4. Expressions and Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 4.1 Primary Expressions 62 4.2 Object and Array Initializers 62 4.3 Function Definition Expressions 63 4.4 Property Access Expressions 64 4.5 Invocation Expressions 66 4.6 Object Creation Expressions 68 4.7 Operator Overview 68 4.8 Arithmetic Expressions 73 4.9 Relational Expressions 78 4.10 Logical Expressions 84 4.11 Assignment Expressions 86 4.12 Evaluation Expressions 88 4.13 Miscellaneous Operators 91 4.14 Summary 96 5. Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 5.1 Expression Statements 98 5.2 Compound and Empty Statements 99 5.3 Conditionals 100 5.4 Loops 105 5.5 Jumps 112 5.6 Miscellaneous Statements 121 5.7 Declarations 124 5.8 Summary of JavaScript Statements 127 6. Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 6.1 Introduction to Objects 129 6.2 Creating Objects 130 6.3 Querying and Setting Properties 133 6.4 Deleting Properties 138 6.5 Testing Properties 139 6.6 Enumerating Properties 140 6.7 Extending Objects 142 6.8 Serializing Objects 143 6.9 Object Methods 144 6.10 Extended Object Literal Syntax 146 6.11 Summary 153 viii | Table of Contents
7. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 7.1 Creating Arrays 156 7.2 Reading and Writing Array Elements 159 7.3 Sparse Arrays 160 7.4 Array Length 161 7.5 Adding and Deleting Array Elements 161 7.6 Iterating Arrays 162 7.7 Multidimensional Arrays 164 7.8 Array Methods 165 7.9 Array-Like Objects 177 7.10 Strings as Arrays 179 7.11 Summary 180 8. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 8.1 Defining Functions 182 8.2 Invoking Functions 186 8.3 Function Arguments and Parameters 193 8.4 Functions as Values 200 8.5 Functions as Namespaces 203 8.6 Closures 204 8.7 Function Properties, Methods, and Constructor 209 8.8 Functional Programming 213 8.9 Summary 219 9. Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 9.1 Classes and Prototypes 222 9.2 Classes and Constructors 224 9.3 Classes with the class Keyword 229 9.4 Adding Methods to Existing Classes 236 9.5 Subclasses 237 9.6 Summary 248 10. Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 10.1 Modules with Classes, Objects, and Closures 250 10.2 Modules in Node 253 10.3 Modules in ES6 255 10.4 Summary 266 11. The JavaScript Standard Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 11.1 Sets and Maps 268 11.2 Typed Arrays and Binary Data 275 11.3 Pattern Matching with Regular Expressions 281 Table of Contents | ix
11.4 Dates and Times 300 11.5 Error Classes 304 11.6 JSON Serialization and Parsing 306 11.7 The Internationalization API 309 11.8 The Console API 317 11.9 URL APIs 320 11.10 Timers 323 11.11 Summary 325 12. Iterators and Generators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 12.1 How Iterators Work 328 12.2 Implementing Iterable Objects 329 12.3 Generators 332 12.4 Advanced Generator Features 336 12.5 Summary 339 13. Asynchronous JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 13.1 Asynchronous Programming with Callbacks 342 13.2 Promises 346 13.3 async and await 367 13.4 Asynchronous Iteration 370 13.5 Summary 377 14. Metaprogramming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 14.1 Property Attributes 380 14.2 Object Extensibility 384 14.3 The prototype Attribute 386 14.4 Well-Known Symbols 387 14.5 Template Tags 395 14.6 The Reflect API 397 14.7 Proxy Objects 399 14.8 Summary 406 15. JavaScript in Web Browsers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 15.1 Web Programming Basics 411 15.2 Events 426 15.3 Scripting Documents 437 15.4 Scripting CSS 452 15.5 Document Geometry and Scrolling 459 15.6 Web Components 464 15.7 SVG: Scalable Vector Graphics 477 15.8 Graphics in a <canvas> 484 x | Table of Contents
15.9 Audio APIs 507 15.10 Location, Navigation, and History 509 15.11 Networking 518 15.12 Storage 536 15.13 Worker Threads and Messaging 548 15.14 Example: The Mandelbrot Set 555 15.15 Summary and Suggestions for Further Reading 568 16. Server-Side JavaScript with Node. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577 16.1 Node Programming Basics 578 16.2 Node Is Asynchronous by Default 583 16.3 Buffers 586 16.4 Events and EventEmitter 588 16.5 Streams 590 16.6 Process, CPU, and Operating System Details 601 16.7 Working with Files 602 16.8 HTTP Clients and Servers 613 16.9 Non-HTTP Network Servers and Clients 617 16.10 Working with Child Processes 620 16.11 Worker Threads 625 16.12 Summary 634 17. JavaScript Tools and Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635 17.1 Linting with ESLint 636 17.2 JavaScript Formatting with Prettier 637 17.3 Unit Testing with Jest 638 17.4 Package Management with npm 640 17.5 Code Bundling 642 17.6 Transpilation with Babel 644 17.7 JSX: Markup Expressions in JavaScript 645 17.8 Type Checking with Flow 649 17.9 Summary 665 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 Table of Contents | xi
(This page has no text content)
Preface This book covers the JavaScript language and the JavaScript APIs implemented by web browsers and by Node. I wrote it for readers with 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. My goal with this book is to document the JavaScript language comprehen‐ sively and definitively and to provide an in-depth introduction to the most important client-side and server-side APIs available to JavaScript programs. As a result, this is a long 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 pro‐ gramming productivity. Previous editions of this book included a comprehensive reference section. I no longer feel that it makes sense to include that material in printed form when it is so quick and easy to find up-to-date reference material online. If you need to look up anything related to core or client-side JavaScript, I recommend you visit the MDN website. And for server-side Node APIs, I recommend you go directly to the source and consult the Node.js reference documentation. Conventions Used in This Book I use the following typographical conventions in this book: Italic Is used for emphasis and to indicate the first use of a term. Italic is also used for email addresses, URLs, and file names. Constant width Is used in all JavaScript code and CSS and HTML listings, and generally for any‐ thing that you would type literally when programming. xiii
Constant width italic Is occasionally used when explaining JavaScript syntax. Constant width bold Shows commands or other text that should be typed literally by the user This element signifies a general note. This element indicates a warning or caution. Example Code Supplemental material (code examples, exercises, etc.) for this book is available for download at: https://oreil.ly/javascript_defgd7 This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us 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 examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “JavaScript: The Defini‐ tive Guide, Seventh Edition, by David Flanagan (O’Reilly). Copyright 2020 David Fla‐ nagan, 978-1-491-95202-3.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. xiv | Preface
O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit http://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/javascript_defgd7. Email bookquestions@oreilly.com to comment or ask technical questions about this book. For news and more information about our books and courses, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments Many people have helped with the creation of this book. I’d like to thank my editor, Angela Rufino, for keeping me on track and for her patience with my missed dead‐ lines. Thanks also to my technical reviewers: Brian Sletten, Elisabeth Robson, Ethan Flanagan, Maximiliano Firtman, Sarah Wachs, and Schalk Neethling. Their com‐ ments and suggestions have made this a better book. Preface | xv
The production team at O’Reilly has done their usual fine job: Kristen Brown man‐ aged the production process, Deborah Baker was the production editor, Rebecca Demarest drew the figures, and Judy McConville created the index. Editors, reviewers, and contributors to previous editions of this book have included: Andrew Schulman, Angelo Sirigos, Aristotle Pagaltzis, Brendan Eich, Christian Heil‐ mann, Dan Shafer, Dave C. Mitchell, Deb Cameron, Douglas Crockford, Dr. Tankred Hirschmann, Dylan Schiemann, Frank Willison, Geoff Stearns, Herman Venter, Jay Hodges, Jeff Yates, Joseph Kesselman, Ken Cooper, Larry Sullivan, Lynn Rollins, Neil Berkman, Mike Loukides, Nick Thompson, Norris Boyd, Paula Ferguson, Peter-Paul Koch, Philippe Le Hegaret, Raffaele Cecco, Richard Yaker, Sanders Kleinfeld, Scott Furman, Scott Isaacs, Shon Katzenberger, Terry Allen, Todd Ditchendorf, Vidur Apparao, Waldemar Horwat, and Zachary Kessin. Writing this seventh edition 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, March 2020 xvi | Preface
CHAPTER 1 Introduction to JavaScript JavaScript is the programming language of the web. The overwhelming majority of websites use JavaScript, and all modern web browsers—on desktops, tablets, and phones—include JavaScript interpreters, making JavaScript the most-deployed pro‐ gramming language in history. Over the last decade, Node.js has enabled JavaScript programming outside of web browsers, and the dramatic success of Node means that JavaScript is now also the most-used programming language among software devel‐ opers. Whether you’re starting from scratch or are already using JavaScript professio‐ nally, this book will help you master the language. If you are already familiar with other programming languages, it may help you to know that JavaScript is a high-level, dynamic, interpreted programming language that is well-suited to object-oriented and functional programming styles. JavaScript’s vari‐ ables are untyped. Its syntax is loosely based on Java, but the languages are otherwise unrelated. JavaScript derives its first-class functions from Scheme and its prototype- based inheritance from the little-known language Self. But you do not need to know any of those languages, or be familiar with those terms, to use this book and learn JavaScript. The name “JavaScript” is quite misleading. Except for a superficial syntactic resem‐ blance, JavaScript is completely different from the Java programming language. And JavaScript has long since outgrown its scripting-language roots to become a robust and efficient general-purpose language suitable for serious software engineering and projects with huge codebases. 1
JavaScript: Names, Versions, and Modes 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 Association—and because of trademark issues, the standardized version of the lan‐ guage was stuck with the awkward name “ECMAScript.” In practice, everyone just calls the language JavaScript. This book uses the name “ECMAScript” and the abbre‐ viation “ES” to refer to the language standard and to versions of that standard. For most of the 2010s, version 5 of the ECMAScript standard has been supported by all web browsers. This book treats ES5 as the compatibility baseline and no longer discusses earlier versions of the language. ES6 was released in 2015 and added major new features—including class and module syntax—that changed JavaScript from a scripting language into a serious, general-purpose language suitable for large-scale software engineering. Since ES6, the ECMAScript specification has moved to a yearly release cadence, and versions of the language—ES2016, ES2017, ES2018, ES2019, and ES2020—are now identified by year of release. As JavaScript evolved, the language designers attempted to correct flaws in the early (pre-ES5) versions. In order to maintain backward compatibility, it is not possible to remove legacy features, no matter how flawed. But in ES5 and later, programs can opt in to JavaScript’s strict mode in which a number of early language mistakes have been corrected. The mechanism for opting in is the “use strict” directive described in §5.6.3. That section also summarizes the differences between legacy JavaScript and strict JavaScript. In ES6 and later, the use of new language features often implicitly invokes strict mode. For example, if you use the ES6 class keyword or create an ES6 module, then all the code within the class or module is automatically strict, and the old, flawed features are not available in those contexts. This book will cover the legacy features of JavaScript but is careful to point out that they are not available in strict mode. To be useful, every language must have a platform, or standard library, for perform‐ ing things like basic input and output. The core JavaScript language defines a mini‐ mal API for working with numbers, text, arrays, sets, maps, and so on, but does not include any input or output functionality. Input and output (as well as more sophisti‐ cated features, such as networking, storage, and graphics) are the responsibility of the “host environment” within which JavaScript is embedded. The original host environment for JavaScript was a web browser, and this is still the most common execution environment for JavaScript code. The web browser environ‐ ment allows JavaScript code to obtain input from the user’s mouse and keyboard and 2 | Chapter 1: Introduction to JavaScript