Learning JavaScript - Holla.cz

Transcription

3rdEditionLearningJavaScriptADD SPARKLE AND LIFE TO YOUR WEB PAGESEthan Brownwww.allitebooks.com

www.allitebooks.com

THIRD EDITIONLearning JavaScriptEthan BrownBeijingBoston FarnhamSebastopolwww.allitebooks.comTokyo

Learning JavaScriptby Ethan BrownCopyright 2016 Ethan Brown. 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 arealso available for most titles (http://safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.Editor: Meg FoleyProduction Editor: Kristen BrownCopyeditor: Rachel MonaghanProofreader: Jasmine KwitynOctober 2006:December 2008:March 2016:Indexer: Judith McConvilleInterior Designer: David FutatoCover Designer: Karen MontgomeryIllustrator: Rebecca DemarestFirst EditionSecond EditionThird EditionRevision History for the Third Edition2016-02-12:First ReleaseSee http://oreilly.com/catalog/errata.csp?isbn 9781491914915 for release details.The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning JavaScript, the cover image ofa baby rhino, and related trade dress are trademarks of O’Reilly Media, Inc.While the publisher and the author have used good faith efforts to ensure that the information andinstructions contained in this work are accurate, the publisher and the author disclaim all responsibilityfor errors or omissions, including without limitation responsibility for damages resulting from the use ofor reliance on this work. Use of the information and instructions contained in this work is at your ownrisk. If any code samples or other technology this work contains or describes is subject to open sourcelicenses or the intellectual property rights of others, it is your responsibility to ensure that your usethereof complies with such licenses and/or rights.978-1-491-91491-5[LSI]www.allitebooks.com

For Mark—a true friend, and fellow creator.www.allitebooks.com

www.allitebooks.com

Table of ContentsPreface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv1. Your First Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Where to StartThe ToolsA Comment on CommentsGetting StartedThe JavaScript ConsolejQueryDrawing Graphics PrimitiveAutomating Repetitive TasksHandling User InputHello, World22457891112132. JavaScript Development Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Writing ES6 TodayES6 FeaturesInstalling GitThe TerminalYour Project RootVersion Control: GitPackage Management: npmBuild Tools: Gulp and GruntProject StructureThe TranscompilersRunning Babel with w.allitebooks.com

3. Literals, Variables, Constants, and Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Variables and ConstantsVariables or Constants: Which to Use?Identifier NamesLiteralsPrimitive Types and ObjectsNumbersStringsEscapingSpecial CharactersTemplate StringsMultiline StringsNumbers as StringsBooleansSymbolsnull and undefinedObjectsNumber, String, and Boolean ObjectsArraysTrailing Commas in Objects and ArraysDatesRegular ExpressionsMaps and SetsData Type ConversionConverting to NumbersConverting to StringConverting to 8495051515252525353544. Control Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55A Control Flow Primerwhile LoopsBlock StatementsWhitespaceHelper Functionsif else Statementdo while Loopfor Loopif StatementPutting It All TogetherControl Flow Statements in JavaScriptControl Flow Exceptionsvi Table of 8

Chaining if.else StatementsMetasyntaxAdditional for Loop Patternsswitch Statementsfor.in loopfor.of loopUseful Control Flow PatternsUsing continue to Reduce Conditional NestingUsing break or return to Avoid Unnecessary ComputationUsing Value of Index After Loop CompletionUsing Descending Indexes When Modifying ListsConclusion6969717275757676767777785. Expressions and Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79OperatorsArithmetic OperatorsOperator PrecedenceComparison OperatorsComparing NumbersString ConcatenationLogical OperatorsTruthy and Falsy ValuesAND, OR, and NOTShort-Circuit EvaluationLogical Operators with Nonboolean OperandsConditional OperatorComma OperatorGrouping OperatorBitwise Operatorstypeof Operatorvoid OperatorAssignment OperatorsDestructuring AssignmentObject and Array OperatorsExpressions in Template StringsExpressions and Control Flow PatternsConverting if.else Statements to Conditional ExpressionsConverting if Statements to Short-Circuited Logical OR 395969698991001001001011016. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Return Values104Table of Contentswww.allitebooks.com vii

Calling Versus ReferencingFunction ArgumentsDo Arguments Make the Function?Destructuring ArgumentsDefault ArgumentsFunctions as Properties of ObjectsThe this KeywordFunction Expressions and Anonymous FunctionsArrow Notationcall, apply, and bindConclusion1041051071081091091101121131141167. Scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117Scope Versus ExistenceLexical Versus Dynamic ScopingGlobal ScopeBlock ScopeVariable MaskingFunctions, Closures, and Lexical ScopeImmediately Invoked Function ExpressionsFunction Scope and HoistingFunction HoistingThe Temporal Dead ZoneStrict 8. Arrays and Array Processing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131A Review of ArraysArray Content ManipulationAdding or Removing Single Elements at the Beginning or EndAdding Multiple Elements at the EndGetting a SubarrayAdding or Removing Elements at Any PositionCutting and Replacing Within an ArrayFilling an Array with a Specific ValueReversing and Sorting ArraysArray SearchingThe Fundamental Array Operations: map and filterArray Magic: reduceArray Methods and Deleted or Never-Defined ElementsString JoiningConclusionviii Table of 5135136138140143143144

9. Objects and Object-Oriented Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147Property Enumerationfor.inObject.keysObject-Oriented ProgrammingClass and Instance CreationDynamic PropertiesClasses Are FunctionsThe PrototypeStatic MethodsInheritancePolymorphismEnumerating Object Properties, RevisitedString RepresentationMultiple Inheritance, Mixins, and 15715815915916110. Maps and Sets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163MapsWeak MapsSetsWeak SetsBreaking the Object Habit16316516616716711. Exceptions and Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169The Error ObjectException Handling with try and catchThrowing ErrorsException Handling and the Call Stacktry.catch.finallyLet Exceptions Be Exceptional16917017117117317412. Iterators and Generators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175The Iteration ProtocolGeneratorsyield Expressions and Two-Way CommunicationGenerators and returnConclusion17717918018218213. Functions and the Power of Abstract Thinking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183Functions as SubroutinesFunctions as Subroutines That Return a Value183184Table of Contents ix

Functions as FunctionsSo What?Functions Are ObjectsIIFEs and Asynchronous CodeFunction VariablesFunctions in an ArrayPass a Function into a FunctionReturn a Function from a 519619714. Asynchronous Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199The AnalogyCallbackssetInterval and clearIntervalScope and Asynchronous ExecutionError-First CallbacksCallback HellPromisesCreating PromisesUsing PromisesEventsPromise ChainingPreventing Unsettled PromisesGeneratorsOne Step Forward and Two Steps Back?Don’t Write Your Own Generator RunnerException Handling in Generator 21121221521621621715. Date and Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219Dates, Time Zones, Timestamps, and the Unix EpochConstructing Date ObjectsMoment.jsA Practical Approach to Dates in JavaScriptConstructing DatesConstructing Dates on the ServerConstructing Dates in the BrowserTransmitting DatesDisplaying DatesDate ComponentsComparing Datesx Table of Contents219220221222222222223223224225226

Date ArithmeticUser-Friendly Relative DatesConclusion22622722716. Math. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229Formatting NumbersFixed DecimalsExponential NotationFixed PrecisionDifferent BasesAdvanced Number FormattingConstantsAlgebraic FunctionsExponentiationLogarithmic FunctionsMiscellaneousPseudorandom Number GenerationTrigonometric FunctionsHyperbolic 617. Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237Substring Matching and ReplacingConstructing Regular ExpressionsSearching with Regular ExpressionsReplacing with Regular ExpressionsInput ConsumptionAlternationMatching HTMLCharacter SetsNamed Character SetsRepetitionThe Period Metacharacter and EscapingA True WildcardGroupingLazy Matches, Greedy MatchesBackreferencesReplacing GroupsFunction ReplacementsAnchoringWord Boundary MatchingLookaheadsConstructing Regexes 248249250251253253254255Table of Contents xi

Conclusion25618. JavaScript in the Browser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257ES5 or ES6?The Document Object ModelSome Tree TerminologyDOM “Get” MethodsQuerying DOM ElementsManipulating DOM ElementsCreating New DOM ElementsStyling ElementsData AttributesEventsEvent Capturing and BubblingEvent 526626727027127419. jQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275The Almighty Dollar (Sign)Including jQueryWaiting for the DOM to LoadjQuery-Wrapped DOM ElementsManipulating ElementsUnwrapping jQuery ObjectsAjaxConclusion27527627627727727928028020. Node. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281Node FundamentalsModulesCore Modules, File Modules, and npm ModulesCustomizing Modules with Function ModulesFilesystem AccessProcessOperating SystemChild ProcessesStreamsWeb ServersConclusionxii Table of Contents281282284287289291294294295297299

21. Object Property Configuration and Proxies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301Accessor Properties: Getters and SettersObject Property AttributesProtecting Objects: Freezing, Sealing, and Preventing ExtensionProxiesConclusion30130330530831022. Additional Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311Online DocumentationPeriodicalsBlogs and TutorialsStack OverflowContributing to Open Source ProjectsConclusion311312312313315315A. Reserved Words. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317B. Operator Precedence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325Table of Contents xiii

PrefaceEven though this is my second book on technologies in the JavaScript ecosystem, Istill find myself somewhat surprised at my role as a JavaScript expert and evangelist.Like so many programmers, I held a strong prejudice against JavaScript up untilabout 2012. To do such an about-face still feels a little disorienting.My prejudice was for the usual reasons: I considered JavaScript a “toy” language(without really learning it properly, and therefore not knowing of what I spoke) thatwas practiced by dangerous, sloppy, untrained amateur programmers. There is a littletruth in both of these reasons. ES6 was developed quickly, and even its inventor Bren‐dan Eich admits there are things that he didn’t get right the first time around—and bythe time he realized it, too many people were relying on the problematic behavior forhim to effectively change it (show me the language that doesn’t suffer from this prob‐lem, however). As for the second reason, JavaScript did make programming suddenlyaccessible. Not only did everyone have a browser, but with only a little effort, theycould see the JavaScript that enabled the websites that were rapidly proliferating onthe Web. People learned by tri

Learning JavaScript by Ethan Brown Copyright 2016 Ethan Brown. 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