《Pro JavaScript Techniques, Second Edition完整原版文件.docx》由会员分享,可在线阅读,更多相关《Pro JavaScript Techniques, Second Edition完整原版文件.docx(181页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、uponthemake,model,andversionofbrowservisitingsaidprogrammerswebsite.Bythemid-2000s,thebrowserwarsofthe90shad beeneasilywonbyInternetExplorer,andbrowserdevelopmentstagnated.Twobrowserschallengedthisstateofaffairs:MozillaFirefoxandGoogleChrome.FirefoxwasthedescendantofNetscape,oneoftheearliestwebbrows
2、ers.ChromehadGooglesbacking,morethanenoughtomakeitaninstantplayeronthescene.ButbothofthesebrowsersmadeafewdesigndecisionsthatfacilitatedtheJavaScriptrevolution.Thefirstdecision was tosupportthe World WideWebconsortiumsimplementation ofvariousstandards.WhetherdealingwiththeDOM,eventhandling,orAjax,Ch
3、romeandFirefoxgenerallyfollowedthespecandimplementeditaswellaspossible.Forprogrammers,thismeantthatwedidnthavetowriteseparatecodeforFirefoxandChrome.WewerealreadyusedtowritingseparatecodeforIEandsomethingelse,sohavingbranchingcodeinitselfwasnotnew.Butmakingsurethatthebranchingwasnotoverlycomplexwasa
4、 welcomerelief.Speakingofstandards,FirefoxandChromealsoputinalotofworkwiththeEuropeanComputerManufacturersAssociation(ECMA,nowstyledEcma).EcmaisthestandardsbodythatoverseesJavaScript.(Tobetechnical,EcmaoverseestheECMAScriptstandard,sinceJavaScriptisatrademarkofOracleandwell,wedontreallycareaboutthos
5、edetails,dowe?WewilluseJavaScripttorefertothelanguageandECMAScripttorefertothespecificationtowhichaJavaScriptimplementationadheres.)ECMAScriptstandardshadlanguishedinmuchthesamewayasIEdevelopment.Withtheriseofrealbrowsercompetition,theECMAScriptstandardwastakenupagain.ECMAScriptversion5(2009)codifie
6、dmanyofthechangesthathadbeenmadeinthetenyears(!)sincethepreviousversionofthestandard.Thegroupitselfwasalsoenergized,withversion5.1comingoutin2011.Thefutureisprovidedfor,withsignificantworkcurrentlybeingdoneonbothversions6and7ofthestandard.Togivecreditwherecreditisdue,ChromepushedtheupdatingofJavaScr
7、iptaswell.TheChromeJavaScriptengine,calledV8,wasaveryimportantpartofChromesdebutin2008.TheChrometeambuiltanenginethatwasmuchfasterthanmostJavaScriptengines,andithaskeptthatgoalatthetopofthelistforsubsequentversions.Infact,theV8enginewassoimpressivethatitbecamethecoreofNode.js,abrowser-independentJav
8、aScriptinterpreter.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 conceptoftheevergreenap
9、plication.Instead ofhavingtodownloadaseparatebrowserinstallforupdates,Chromesdefaultistoautomaticallyupdatethebrowserforyou.Whilethisapproachissometimesapaininthecorporate world,itisa greatboon tothe noncorporate consumersurfer(also known as aperson!).Ifyou useChrome(and,forthelastfewyears,Firefox),
10、yourbrowserisup-to-date,withoutyourhavingtomakeanyeffort.WhileMicrosofthasdonethisforalongtimeinpushingsecurityupdatesviaWindowsUpdate,itdoesnotintroducenewfeaturestoInternetExplorerunlesstheyarecoupledtoanewversionofWindows.Toputitanotherway,updatestoIEareslowincoming.ChromeandFirefoxalwayshavethel
11、atestandgreatestfeatures,aswellasbeingquitesecure.AsGooglepressedonwith Chromesfeatures,theotherbrowsermakersplayed catch-up.Sometimesthiscameinsillierways,suchaswhenFirefoxadaptedChromesversionnumbering.ButitalsoresultedinMozillaandMicrosofttakingacold,hardlookatJavaScriptengines.Bothbrowsermakersh
12、avesignificantlyoverhauledtheirJSenginesoverthelastfewyears,andChromeslead,whileformidable,isnolongerinsurmountable.Finally,Microsofthas(mostly)thrownin thetowelon its classic“embraceand extend”philosophy,atleastwhen itcomestoJavaScript.With IEversion9,Microsoftimplemented World WideWebConsortium(W3
13、C)eventhandlingand standardized itsDOM interfacesaswell asits AjaxAPI.FormostofthestandardfeaturesofJavaScript,wenolongerhavetoimplementtwoversionsofthesamecode!(Legacycodeforlegacybrowsersisstillabitofanissue,ofcourse)Itseemsalmostapanacea.JavaScriptisfasterthaneverbefore.Itiseasiertowritecodeforav
14、arietyofdifferentbrowsers.Standardsdocumentsbothdescribetherealworldandprovideausefulroadmaptofeaturestocome.Andmostofourbrowsersarefullyup-to-date.Sowhatdoweneedtoworryaboutnow,andwhere arewegoingin thefuture?2Modern JavaScriptChapter1professionalJavasCriptteChniquesIthasneverbeeneasiertodevelopser
15、iousapplicationswithJavaScript.Wehaveaclear,cleanbreakwiththebadolddaysofseparatecodeformultiplebrowsers,poorstandardspoorlyimplemented,andslowJavaScriptenginesthatwereoftenanafterthought.LetstakealookatthestateofthemodernJavaScriptenvironment.Specifically,wewilllookattwoareas:themodernbrowserandthe
16、moderntoolkit.ModernJavaScriptdependsontheideaofthe modernbrowser.Whatisthemodernbrowser?Differentorganizationsdescribeitindifferentways.Googlesaysthattheirapplicationssupportthecurrentandpreviousmajorversionsofbrowsers.(Fascinating,asGmailstillworksonIE9,asfaraswecantell!)Inaninterestingarticle,the
17、peoplebehind theBritish BroadcastingCompany(BBC)websiterevealed thattheydefineamodernbrowserasonethatsupportsthefollowingcapabilities:1.document.querySelector()/document.querySelectorAll()2.window.addEventListener()3.TheStorageAPI(localStorageandsessionStorage)jQuery,probablythemostpopularJavaScript
18、libraryontheweb,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 updateona
19、fasterschedulethan IEanddonthavenearlythemarketshareitdoes.Sowhere isthe borderline forthe modern browser?Alas,the borderseems to wanderbetween InternetExplorerversions9through11.ButIE8isdefinitelyonthefarsideofbrowserhistory.ItdoesnotsupportmostofthefeaturesofECMAScript5.ItdoesnotincludetheAPIforW3
20、Ceventhandling.Thelistgoesonand on.Sowhenwediscussmodernbrowsers,wewillrefertoatleastInternetExplorer9.And ourcoveragewillnotendeavortosupportancientbrowsers.Whererelevantandsimple,wewillpointoutpolyfillsforolderversionsofIE,butingeneral,ourfloorisInternetExplorer9.The Rise of LibrariesInadditiontot
21、hemodernbrowser,thereisanotherimportantaspectofthecurrentenvironmentforJavaScriptweneedtodiscuss:libraries.Overthepast8years,therehasbeenanexplosioninthenumberandvarietyofJavaScriptlibraries.Therearemorethan800,000GitHubrepositoriesforJavaScript;ofthese,almost900havemorethan1,000stars.Fromitshumbleb
22、eginningsascollectionsofutilityfunctions,theJavaScriptlibraryecosystemhasevolved(somewhatchaotically)intoavastlandscapeofpossibilities.HowdoesthisaffectusasJavaScriptdevelopers?Well,ofcourse,thereisthemodelof“libraryasexpansion,”wherealibraryprovidesadditionalfunctionality.Think oftheMVClibrarieslik
23、eBackboneand Angular(which wewill belooking atin alaterchapter),orthe data visualizationlibraries liked3 orHighcharts.ButJavaScriptisinaninterestingposition,aslibrariescanalsoprovidealevelinterfacetofeaturesthatarestandardonsomebrowsersbutnotonothers.Foralongtime,thestandardexampleofavariablyimpleme
24、ntedfeatureinJavaScriptwaseventhandling.InternetExplorerhad itsownevent-handling API.Otherbrowsersgenerallyfollowed theW3CsAPI.Variouslibrariesprovidedunifiedimplementationsforeventhandling,includingthebestofbothworlds.Someoftheselibrariesstoodalone,butthesuccessfulonesalsonormalizedfunctionalityfor
25、Ajax,theDOM,andanumberofotherfeaturesthatweredifferentlyimplementedacrossbrowsers.ThemostpopularoftheselibrarieshasbeenjQuery.Sinceitsinception,jQueryhasbeenthego-tolibraryforusingnewJavaScriptfeatureswithoutworryingaboutthebrowserssupportforthosefeatures.Soinstead ofusing IEsevent handling orthe W3
26、Cs,you could simply usejQuerys.on()function,whichwrappedaroundthevariance,providingaunifiedinterface.Severalotherlibrariesprovidedsimilarfunctionality:Dojo,ExtJS,Prototype,YUI,MooTools,andsoon.ThesetoolkitlibrariesaimedtostandardizeAPIs fordevelopers.3Chapter1professionalJavasCriptteChniquesThe stan
27、dardization 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.Wherelibraries
28、couldfixorworkaroundthesebugs,theydid.Forexample,jQuery1.11containsmorethanahalf-dozenfixesforproblemswiththeevent-handlingAPI.Somelibraries(jQueryinparticular)alsoprovidednewordifferentinterpretationsofcertaincapabilities.The jQuery selector function,the core of the library,predates the now-standar
29、dquerySelector()andquerySelectorAll()functions,anditwasadriverforincludingthosefunctionsinJavaScript.Otherlibrariesprovideaccesstofunctionalitydespiteverydifferentunderlyingimplementations.Laterinthebook,wewilllookatAjaxsnewCrossOriginResourceSharing(CORS)protocol,whichallowsforAjaxrequeststoservers
30、otherthantheonethatoriginallyservedthepage.SomelibrarieshavealreadyimplementedaversionofthisthatusesCORS butfallsbacktoJSONwithpadding(JSON-P)whereneeded.Becauseoftheirutility,somelibrarieshavebecomepartofaprofessionalJavaScriptprogrammersstandarddevelopmenttoolkit.Theirfeaturesmaynotbestandardizedi
31、ntoJavaScript(yet),buttheyareanaccumulationofknowledgeandfunctionalitythatsimplymakesiteasiertorealizedesignsquickly.Inrecentyears,though,youcouldgetquiteafewhitstoyourblogbyaskingwhetherjQuery(oranotherlibrary)wasreallynecessaryfordevelopmentonamodern browser.ConsidertheBBCsrequirements;youcan cert
32、ainlyrealizealargedegreeofjQuery-likefunctionalityifyouhavethosethreemethodsavailabletoyou.ButjQuery alsoincludesa simplified yet expanded DOM interface,ithandles bugsfora variety ofdifferentedgecases,and ifyou need supportforIE8 orearlier,jQueryis yourmajoroption.Accordingly,theprofessionalJavaScri
33、ptprogrammermustlookattherequirementsforaprojectandconsiderwhetheritpaystoriskreinventingthewheelthatjQuery(oranothersimilarlibrary)provides.More Than a Note about MobileInolderJavaScript and web developmentbooks,you would reliablyseeasection,maybea whole chapter,onwhatto doaboutmobile browsing.Mobi
34、lebrowsing was asmall enough share oftotal browsing,and themarketwassofractured,thatitseemed only specialistswouldbeinterestedinmobile development.Thatsnotthecaseanymore.Sincethefirsteditionofthisbook,mobilewebbrowsinghasexploded,anditisaverydifferentbeastfromdesktopdevelopment.Considersomestatistic
35、s:accordingtoavarietyofsources,mobilebrowsing representsbetween20 and30percentofallbrowsing.Bythetimeyou arereadingthis,itmaywellrepresentmore,asithasconsistentlyincreasedsincethedebutoftheiPhone.Speakingofwhich,well over40percent ofmobile browsing isdone with iOS Safari,although Androidsbrowserand
36、ChromeforAndroid aregaining ground(and mayhave overtaken Safari,dependingonwhosestats you believe).SafarioniOSisnotthesameas Safarionthedesktop,and the samegoesforAndroid Chromevs.desktopChromeandmobileFirefoxvs.desktopFirefox.Mobileismainstream.Thebrowsersonmobiledevicesprovideanewsetofchallengesan
37、dopportunities.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 deve
38、lopmentrequirements,youmayhavetobuildanappthatlooksgoodonmobileaswellasthedesktop,orreimplementexistingfunctionalityfor amobileplatform.TheJavaScriptlandscapehaschangedextensivelyoverthelastfewyears.DespitesomestandardizationofAPIs,therearealsomanynewchallenges.HowwillthisaffectusasprofessionalJavaS
39、criptprogrammers?4WhereDoWeGofromHere?Chapter1professionalJavasCriptteChniquesWeshould setdownsome standardsforourselves.Wehavealready setone:IE9 asthefloorofthemodernbrowserexperience.Theotherbrowsersareevergreen,and nottoworryabout.Whataboutmobile,then?Whiletheissueiscomplex,iOS6and Android4.1(Jel
40、lyBean)will,ingeneral,serveasourfloors.Mobilecomputingupdatesfasterand morefrequentlythandesktopsdo,soweareconfidentinusing thesemorerecentversionsofmobileoperatingsystems.Thatsaid,letusdigressforamomenttodiscussnotbrowserversions,operatingsystems,orplatforms,butyouraudience.Whilewecanquotestatistic
41、salldaylong,thevaluablestatisticstellyouaboutyouraudience,nottheaudiencein general.Perhapsyouaredesigning foryouremployer,whohasstandardizedonIE10.OrmaybeyourideaforanapplicationdependsheavilyonfeaturesthatonlyChromeprovides.Ormaybethereisntevenadesktopversion,butyoureaimingforaroll-outtoiPadsandAnd
42、roidtablets.Consideryourtargetaudience.This bookiswritten tobebroadlyapplicable,and yourapplicationmaybeaswell.ButitwouldbefollytospendtimeworryingaboutbugsinIE9forthatpreviouslymentionedtablet-onlyapplication,wouldntit?Now,backtoourstandards.Forscreenshotsandtesting,thisbookwillgenerallypreferGoogl
43、eChrome.Occasionally,wewilldemonstratecodeonFirefoxorInternetExplorerwhereitisrelevant.Chrome,fordevelopers,isthegoldstandardnotnecessarilyinuser-friendliness,butcertainlyintheinformationexposedtotheprogrammer.Inalaterchapter,wewilllookatthevariousdevelopertoolsavailable,scrutinizingnotonlyChrome,bu
44、tFirefox(withandwithoutFirebug)andIEaswell.Asastandardlibrary,wewillrefertojQuery.Therearemanyalternatives,ofcourse,butjQuerywinsfortworeasons:first,itisthemostpopulargeneral-useJavaScriptlibraryontheweb.Second,atleastoneoftheauthors(JohnResig)hasalittle bitofhistorywithjQuery,which predisposedthe o
45、therauthor(JohnPaxton)toconcedethepointofworkingwithit.Inupdatingthisbook,wehavereplacedmanyofthetechniquesfromthepreviousversionwithjQueryslibraryoffunctionality.Inthesecases,wearedisinclinedtoreinventthewheel.Asneeded,wewillrefertotheappropriatejQueryfunctionality.Wewill,ofcourse,discussnewandexci
46、tingtechniques,aswell!JavaScriptIDEshaveupdatedsignificantly in the lastfewyears,driven byJavaScriptsownrise.Thepossibilitiesaretoonumeroustolisthere,butthereareafewapplicationsofnote.John Resigusesahighlycustomized versionofvim forhis developmentenvironment.John Paxton isalittle bitlazier,and has e
47、lectedtouseJetBrainsexcellentWebStorm(open source,free Brackets IDE(brackets.io/),currently at version 1.3.Eclipse is also available,andmanypeoplehavereportedpositiveresultsbycustomizingSublimeTextorEmacstodotheirbidding.Asalways,usewhatyoufeelmostcomfortablewith.ThereareothertoolsthatcanassistinJav
48、aScriptdevelopment.Ratherthanlistthemhere,wewilldedicateachaptertothemlaterinthebook.Whichmeansitsagoodtimetogiveanoutlineofwhatsto come.Coming Up NextStartingwithChapter2,wewilllookatthelatestandgreatestintheJavaScriptlanguage.Thismeanslookingatnew featureslike those available through theObjecttype
49、,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()me
50、thod,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