Pro JavaScript Techniques, Second Edition完整原版文件.docx
uponthemake,model,andversionofbrowservisitingsaidprogrammerswebsite.Bythemid-2000s,thebrowserwarsofthe90shad beeneasilywonbyInternetExplorer,andbrowserdevelopmentstagnated.Twobrowserschallengedthisstateofaffairs:MozillaFirefoxandGoogleChrome.FirefoxwasthedescendantofNetscape,oneoftheearliestwebbrowsers.ChromehadGooglesbacking,morethanenoughtomakeitaninstantplayeronthescene.ButbothofthesebrowsersmadeafewdesigndecisionsthatfacilitatedtheJavaScriptrevolution.Thefirstdecision was tosupportthe World WideWebconsortiumsimplementation ofvariousstandards.WhetherdealingwiththeDOM,eventhandling,orAjax,ChromeandFirefoxgenerallyfollowedthespecandimplementeditaswellaspossible.Forprogrammers,thismeantthatwedidnthavetowriteseparatecodeforFirefoxandChrome.WewerealreadyusedtowritingseparatecodeforIEandsomethingelse,sohavingbranchingcodeinitselfwasnotnew.Butmakingsurethatthebranchingwasnotoverlycomplexwasa welcomerelief.Speakingofstandards,FirefoxandChromealsoputinalotofworkwiththeEuropeanComputerManufacturersAssociation(ECMA,nowstyledEcma).EcmaisthestandardsbodythatoverseesJavaScript.(Tobetechnical,EcmaoverseestheECMAScriptstandard,sinceJavaScriptisatrademarkofOracleandwell,wedontreallycareaboutthosedetails,dowe?WewilluseJavaScripttorefertothelanguageandECMAScripttorefertothespecificationtowhichaJavaScriptimplementationadheres.)ECMAScriptstandardshadlanguishedinmuchthesamewayasIEdevelopment.Withtheriseofrealbrowsercompetition,theECMAScriptstandardwastakenupagain.ECMAScriptversion5(2009)codifiedmanyofthechangesthathadbeenmadeinthetenyears(!)sincethepreviousversionofthestandard.Thegroupitselfwasalsoenergized,withversion5.1comingoutin2011.Thefutureisprovidedfor,withsignificantworkcurrentlybeingdoneonbothversions6and7ofthestandard.Togivecreditwherecreditisdue,ChromepushedtheupdatingofJavaScriptaswell.TheChromeJavaScriptengine,calledV8,wasaveryimportantpartofChromesdebutin2008.TheChrometeambuiltanenginethatwasmuchfasterthanmostJavaScriptengines,andithaskeptthatgoalatthetopofthelistforsubsequentversions.Infact,theV8enginewassoimpressivethatitbecamethecoreofNode.js,abrowser-independentJavaScriptinterpreter.OriginallyintendedasaserverthatwoulduseJavaScriptasits main application language,Nodehas become aflexible platform forrunning any number ofJavaScript-based applications.Back to Chrome:the other major innovation Googleintroduced to the land ofbrowserswas the conceptoftheevergreenapplication.Instead ofhavingtodownloadaseparatebrowserinstallforupdates,Chromesdefaultistoautomaticallyupdatethebrowserforyou.Whilethisapproachissometimesapaininthecorporate world,itisa greatboon tothe noncorporate consumersurfer(also known as aperson!).Ifyou useChrome(and,forthelastfewyears,Firefox),yourbrowserisup-to-date,withoutyourhavingtomakeanyeffort.WhileMicrosofthasdonethisforalongtimeinpushingsecurityupdatesviaWindowsUpdate,itdoesnotintroducenewfeaturestoInternetExplorerunlesstheyarecoupledtoanewversionofWindows.Toputitanotherway,updatestoIEareslowincoming.ChromeandFirefoxalwayshavethelatestandgreatestfeatures,aswellasbeingquitesecure.AsGooglepressedonwith Chromesfeatures,theotherbrowsermakersplayed catch-up.Sometimesthiscameinsillierways,suchaswhenFirefoxadaptedChromesversionnumbering.ButitalsoresultedinMozillaandMicrosofttakingacold,hardlookatJavaScriptengines.BothbrowsermakershavesignificantlyoverhauledtheirJSenginesoverthelastfewyears,andChromeslead,whileformidable,isnolongerinsurmountable.Finally,Microsofthas(mostly)thrownin thetowelon its classic“embraceand extend”philosophy,atleastwhen itcomestoJavaScript.With IEversion9,Microsoftimplemented World WideWebConsortium(W3C)eventhandlingand standardized itsDOM interfacesaswell asits AjaxAPI.FormostofthestandardfeaturesofJavaScript,wenolongerhavetoimplementtwoversionsofthesamecode!(Legacycodeforlegacybrowsersisstillabitofanissue,ofcourse)Itseemsalmostapanacea.JavaScriptisfasterthaneverbefore.Itiseasiertowritecodeforavarietyofdifferentbrowsers.Standardsdocumentsbothdescribetherealworldandprovideausefulroadmaptofeaturestocome.Andmostofourbrowsersarefullyup-to-date.Sowhatdoweneedtoworryaboutnow,andwhere arewegoingin thefuture?2Modern JavaScriptChapter1professionalJavasCriptteChniquesIthasneverbeeneasiertodevelopseriousapplicationswithJavaScript.Wehaveaclear,cleanbreakwiththebadolddaysofseparatecodeformultiplebrowsers,poorstandardspoorlyimplemented,andslowJavaScriptenginesthatwereoftenanafterthought.LetstakealookatthestateofthemodernJavaScriptenvironment.Specifically,wewilllookattwoareas:themodernbrowserandthemoderntoolkit.ModernJavaScriptdependsontheideaofthe modernbrowser.Whatisthemodernbrowser?Differentorganizationsdescribeitindifferentways.Googlesaysthattheirapplicationssupportthecurrentandpreviousmajorversionsofbrowsers.(Fascinating,asGmailstillworksonIE9,asfaraswecantell!)Inaninterestingarticle,thepeoplebehind theBritish BroadcastingCompany(BBC)websiterevealed thattheydefineamodernbrowserasonethatsupportsthefollowingcapabilities:1.document.querySelector()/document.querySelectorAll()2.window.addEventListener()3.TheStorageAPI(localStorageandsessionStorage)jQuery,probablythemostpopularJavaScriptlibraryontheweb,splititsversionsintothe1.xline,whichsupportsIE6andlater,andthe2.xline,whichsupports“modern”browserslikeIE9andlater.Andmakeno mistake,IEis thedividing line between the modern and the ancient.Theother twomajor browsersareevergreen.And whileSafari and Operaarenotevergreen,they updateonafasterschedulethan IEanddonthavenearlythemarketshareitdoes.Sowhere isthe borderline forthe modern browser?Alas,the borderseems to wanderbetween InternetExplorerversions9through11.ButIE8isdefinitelyonthefarsideofbrowserhistory.ItdoesnotsupportmostofthefeaturesofECMAScript5.ItdoesnotincludetheAPIforW3Ceventhandling.Thelistgoesonand on.Sowhenwediscussmodernbrowsers,wewillrefertoatleastInternetExplorer9.And ourcoveragewillnotendeavortosupportancientbrowsers.Whererelevantandsimple,wewillpointoutpolyfillsforolderversionsofIE,butingeneral,ourfloorisInternetExplorer9.The Rise of LibrariesInadditiontothemodernbrowser,thereisanotherimportantaspectofthecurrentenvironmentforJavaScriptweneedtodiscuss:libraries.Overthepast8years,therehasbeenanexplosioninthenumberandvarietyofJavaScriptlibraries.Therearemorethan800,000GitHubrepositoriesforJavaScript;ofthese,almost900havemorethan1,000stars.Fromitshumblebeginningsascollectionsofutilityfunctions,theJavaScriptlibraryecosystemhasevolved(somewhatchaotically)intoavastlandscapeofpossibilities.HowdoesthisaffectusasJavaScriptdevelopers?Well,ofcourse,thereisthemodelof“libraryasexpansion,”wherealibraryprovidesadditionalfunctionality.Think oftheMVClibrarieslikeBackboneand Angular(which wewill belooking atin alaterchapter),orthe data visualizationlibraries liked3 orHighcharts.ButJavaScriptisinaninterestingposition,aslibrariescanalsoprovidealevelinterfacetofeaturesthatarestandardonsomebrowsersbutnotonothers.Foralongtime,thestandardexampleofavariablyimplementedfeatureinJavaScriptwaseventhandling.InternetExplorerhad itsownevent-handling API.Otherbrowsersgenerallyfollowed theW3CsAPI.Variouslibrariesprovidedunifiedimplementationsforeventhandling,includingthebestofbothworlds.Someoftheselibrariesstoodalone,butthesuccessfulonesalsonormalizedfunctionalityforAjax,theDOM,andanumberofotherfeaturesthatweredifferentlyimplementedacrossbrowsers.ThemostpopularoftheselibrarieshasbeenjQuery.Sinceitsinception,jQueryhasbeenthego-tolibraryforusingnewJavaScriptfeatureswithoutworryingaboutthebrowserssupportforthosefeatures.Soinstead ofusing IEsevent handling orthe W3Cs,you could simply usejQuerys.on()function,whichwrappedaroundthevariance,providingaunifiedinterface.Severalotherlibrariesprovidedsimilarfunctionality:Dojo,ExtJS,Prototype,YUI,MooTools,andsoon.ThesetoolkitlibrariesaimedtostandardizeAPIs fordevelopers.3Chapter1professionalJavasCriptteChniquesThe standardization goes further than providing simple branching code.These libraries oftenameliorate buggy implementations.The official APIfora function may not change much between versions,buttherewillbebugs;sometimesthosebugswillbefixed,sometimesnot,andsometimesthefixeswillintroducenewbugs.Wherelibrariescouldfixorworkaroundthesebugs,theydid.Forexample,jQuery1.11containsmorethanahalf-dozenfixesforproblemswiththeevent-handlingAPI.Somelibraries(jQueryinparticular)alsoprovidednewordifferentinterpretationsofcertaincapabilities.The jQuery selector function,the core of the library,predates the now-standardquerySelector()andquerySelectorAll()functions,anditwasadriverforincludingthosefunctionsinJavaScript.Otherlibrariesprovideaccesstofunctionalitydespiteverydifferentunderlyingimplementations.Laterinthebook,wewilllookatAjaxsnewCrossOriginResourceSharing(CORS)protocol,whichallowsforAjaxrequeststoserversotherthantheonethatoriginallyservedthepage.SomelibrarieshavealreadyimplementedaversionofthisthatusesCORS butfallsbacktoJSONwithpadding(JSON-P)whereneeded.Becauseoftheirutility,somelibrarieshavebecomepartofaprofessionalJavaScriptprogrammersstandarddevelopmenttoolkit.TheirfeaturesmaynotbestandardizedintoJavaScript(yet),buttheyareanaccumulationofknowledgeandfunctionalitythatsimplymakesiteasiertorealizedesignsquickly.Inrecentyears,though,youcouldgetquiteafewhitstoyourblogbyaskingwhetherjQuery(oranotherlibrary)wasreallynecessaryfordevelopmentonamodern browser.ConsidertheBBCsrequirements;youcan certainlyrealizealargedegreeofjQuery-likefunctionalityifyouhavethosethreemethodsavailabletoyou.ButjQuery alsoincludesa simplified yet expanded DOM interface,ithandles bugsfora variety ofdifferentedgecases,and ifyou need supportforIE8 orearlier,jQueryis yourmajoroption.Accordingly,theprofessionalJavaScriptprogrammermustlookattherequirementsforaprojectandconsiderwhetheritpaystoriskreinventingthewheelthatjQuery(oranothersimilarlibrary)provides.More Than a Note about MobileInolderJavaScript and web developmentbooks,you would reliablyseeasection,maybea whole chapter,onwhatto doaboutmobile browsing.Mobilebrowsing was asmall enough share oftotal browsing,and themarketwassofractured,thatitseemed only specialistswouldbeinterestedinmobile development.Thatsnotthecaseanymore.Sincethefirsteditionofthisbook,mobilewebbrowsinghasexploded,anditisaverydifferentbeastfromdesktopdevelopment.Considersomestatistics:accordingtoavarietyofsources,mobilebrowsing representsbetween20 and30percentofallbrowsing.Bythetimeyou arereadingthis,itmaywellrepresentmore,asithasconsistentlyincreasedsincethedebutoftheiPhone.Speakingofwhich,well over40percent ofmobile browsing isdone with iOS Safari,although Androidsbrowserand ChromeforAndroid aregaining ground(and mayhave overtaken Safari,dependingonwhosestats you believe).SafarioniOSisnotthesameas Safarionthedesktop,and the samegoesforAndroid Chromevs.desktopChromeandmobileFirefoxvs.desktopFirefox.Mobileismainstream.Thebrowsersonmobiledevicesprovideanewsetofchallengesandopportunities.Mobiledevicesareoftenmorelimitedthandesktops(thoughthatsanothergapthatisrapidlyclosing).Conversely,mobiledevices offer new features(swipe events,more accurate geolocation,and so on)and new interaction idioms(usingthe hand instead ofthe mouse,swiping forscrolling).Depending onyour developmentrequirements,youmayhavetobuildanappthatlooksgoodonmobileaswellasthedesktop,orreimplementexistingfunctionalityfor amobileplatform.TheJavaScriptlandscapehaschangedextensivelyoverthelastfewyears.DespitesomestandardizationofAPIs,therearealsomanynewchallenges.HowwillthisaffectusasprofessionalJavaScriptprogrammers?4WhereDoWeGofromHere?Chapter1professionalJavasCriptteChniquesWeshould setdownsome standardsforourselves.Wehavealready setone:IE9 asthefloorofthemodernbrowserexperience.Theotherbrowsersareevergreen,and nottoworryabout.Whataboutmobile,then?Whiletheissueiscomplex,iOS6and Android4.1(JellyBean)will,ingeneral,serveasourfloors.Mobilecomputingupdatesfasterand morefrequentlythandesktopsdo,soweareconfidentinusing thesemorerecentversionsofmobileoperatingsystems.Thatsaid,letusdigressforamomenttodiscussnotbrowserversions,operatingsystems,orplatforms,butyouraudience.Whilewecanquotestatisticsalldaylong,thevaluablestatisticstellyouaboutyouraudience,nottheaudiencein general.Perhapsyouaredesigning foryouremployer,whohasstandardizedonIE10.OrmaybeyourideaforanapplicationdependsheavilyonfeaturesthatonlyChromeprovides.Ormaybethereisntevenadesktopversion,butyoureaimingforaroll-outtoiPadsandAndroidtablets.Consideryourtargetaudience.This bookiswritten tobebroadlyapplicable,and yourapplicationmaybeaswell.ButitwouldbefollytospendtimeworryingaboutbugsinIE9forthatpreviouslymentionedtablet-onlyapplication,wouldntit?Now,backtoourstandards.Forscreenshotsandtesting,thisbookwillgenerallypreferGoogleChrome.Occasionally,wewilldemonstratecodeonFirefoxorInternetExplorerwhereitisrelevant.Chrome,fordevelopers,isthegoldstandardnotnecessarilyinuser-friendliness,butcertainlyintheinformationexposedtotheprogrammer.Inalaterchapter,wewilllookatthevariousdevelopertoolsavailable,scrutinizingnotonlyChrome,butFirefox(withandwithoutFirebug)andIEaswell.Asastandardlibrary,wewillrefertojQuery.Therearemanyalternatives,ofcourse,butjQuerywinsfortworeasons:first,itisthemostpopulargeneral-useJavaScriptlibraryontheweb.Second,atleastoneoftheauthors(JohnResig)hasalittle bitofhistorywithjQuery,which predisposedthe otherauthor(JohnPaxton)toconcedethepointofworkingwithit.Inupdatingthisbook,wehavereplacedmanyofthetechniquesfromthepreviousversionwithjQueryslibraryoffunctionality.Inthesecases,wearedisinclinedtoreinventthewheel.Asneeded,wewillrefertotheappropriatejQueryfunctionality.Wewill,ofcourse,discussnewandexcitingtechniques,aswell!JavaScriptIDEshaveupdatedsignificantly in the lastfewyears,driven byJavaScriptsownrise.Thepossibilitiesaretoonumeroustolisthere,butthereareafewapplicationsofnote.John Resigusesahighlycustomized versionofvim forhis developmentenvironment.John Paxton isalittle bitlazier,and has electedtouseJetBrainsexcellentWebStorm(open source,free Brackets IDE(brackets.io/),currently at version 1.3.Eclipse is also available,andmanypeoplehavereportedpositiveresultsbycustomizingSublimeTextorEmacstodotheirbidding.Asalways,usewhatyoufeelmostcomfortablewith.ThereareothertoolsthatcanassistinJavaScriptdevelopment.Ratherthanlistthemhere,wewilldedicateachaptertothemlaterinthebook.Whichmeansitsagoodtimetogiveanoutlineofwhatsto come.Coming Up NextStartingwithChapter2,wewilllookatthelatestandgreatestintheJavaScriptlanguage.Thismeanslookingatnew featureslike those available through theObjecttype,butalso reexamining some olderconcepts likereferences,functions,scope,and closures.Wewill lump all of this under the heading ofFeatures,Functions,andObjects,butitcoversabitmorethanthat.Chapter3discussesCreatingReusableCode.Chapter2skipsoveroneofthebiggestnewfeaturesofJavaScript,theObject.create()method,and its implications forobject-oriented JavaScriptcode.So inthischapter we will spend time withObject.create(),functional constructors,prototypes,and object-orientedconceptsasimplementedinJavaScript.Havingspenttwochaptersdevelopingcode,weshouldstartthinkingabouthowtomanageit.Chapter4shows you t