Pro JavaScript Techniques, Second Edition完整原版文件.docx

上传人:暗伤 文档编号:101404689 上传时间:2024-10-07 格式:DOCX 页数:181 大小:1.91MB
返回 下载 相关 举报
Pro JavaScript Techniques, Second Edition完整原版文件.docx_第1页
第1页 / 共181页
Pro JavaScript Techniques, Second Edition完整原版文件.docx_第2页
第2页 / 共181页
点击查看更多>>
资源描述

《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

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 技术方案

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁