Tải bản đầy đủ (.pdf) (353 trang)

OReilly javascript the good parts may 2008 ISBN 0596517742

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.42 MB, 353 trang )

JavaScript:TheGoodParts
byDouglasCrockford
Publisher:O'Reilly
PubDate:May2,2008
PrintISBN-13:978-0-596-51774-8
Pages:170
TableofContents|Index

Overview
Mostprogramminglanguagescontaingoodandbadparts,but
JavaScripthasmorethanitsshareofthebad,havingbeen
developedandreleasedinahurrybeforeitcouldberefined.
Thisauthoritativebookscrapesawaythesebadfeaturesto
revealasubsetofJavaScriptthat'smorereliable,readable,and
maintainablethanthelanguageasawhole-asubsetyoucan
usetocreatetrulyextensibleandefficientcode.Consideredthe
JavaScriptexpertbymanypeopleinthedevelopment
community,authorDouglasCrockfordidentifiestheabundance
ofgoodideasthatmakeJavaScriptanoutstandingobjectorientedprogramminglanguage-ideassuchasfunctions,loose
typing,dynamicobjects,andanexpressiveobjectliteral
notation.Unfortunately,thesegoodideasaremixedinwithbad
anddownrightawfulideas,likeaprogrammingmodelbasedon
globalvariables.WhenJavaappletsfailed,JavaScriptbecame
thelanguageoftheWebbydefault,makingitspopularity
almostcompletelyindependentofitsqualitiesasa
programminglanguage.InJavaScript:TheGoodParts,
Crockfordfinallydigsthroughthesteamingpileofgood
intentionsandblunderstogiveyouadetailedlookatallthe
genuinelyelegantpartsofJavaScript,including:
Syntax
Objects




Functions
Inheritance
Arrays
Regularexpressions
Methods
Style
Beautifulfeatures
Therealbeauty?Asyoumoveaheadwiththesubsetof
JavaScriptthatthisbookpresents,you'llalsosidesteptheneed
tounlearnallthebadparts.Ofcourse,ifyouwanttofindout
moreaboutthebadpartsandhowtousethembadly,simply
consultanyotherJavaScriptbook.WithJavaScript:TheGood
Parts,you'lldiscoverabeautiful,elegant,lightweightandhighly
expressivelanguagethatletsyoucreateeffectivecode,
whetheryou'remanagingobjectlibrariesorjusttryingtoget
Ajaxtorunfast.Ifyoudevelopsitesorapplicationsforthe
Web,thisbookisanabsolutemust.


JavaScript:TheGoodParts
byDouglasCrockford
Publisher:O'Reilly
PubDate:May2,2008
PrintISBN-13:978-0-596-51774-8
Pages:170
TableofContents|Index

Dedication

Preface
Chapter1.GoodParts
Section1.1.WhyJavaScript?
Section1.2.AnalyzingJavaScript
Section1.3.ASimpleTestingGround
Chapter2.Grammar
Section2.1.Whitespace
Section2.2.Names
Section2.3.Numbers
Section2.4.Strings
Section2.5.Statements
Section2.6.Expressions
Section2.7.Literals
Section2.8.Functions
Chapter3.Objects
Section3.1.ObjectLiterals
Section3.2.Retrieval
Section3.3.Update
Section3.4.Reference
Section3.5.Prototype
Section3.6.Reflection
Section3.7.Enumeration


Section3.8.Delete
Section3.9.GlobalAbatement
Chapter4.Functions
Section4.1.FunctionObjects
Section4.2.FunctionLiteral
Section4.3.Invocation

Section4.4.Arguments
Section4.5.Return
Section4.6.Exceptions
Section4.7.AugmentingTypes
Section4.8.Recursion
Section4.9.Scope
Section4.10.Closure
Section4.11.Callbacks
Section4.12.Module
Section4.13.Cascade
Section4.14.Curry
Section4.15.Memoization
Chapter5.Inheritance
Section5.1.Pseudoclassical
Section5.2.ObjectSpecifiers
Section5.3.Prototypal
Section5.4.Functional
Section5.5.Parts
Chapter6.Arrays
Section6.1.ArrayLiterals
Section6.2.Length
Section6.3.Delete
Section6.4.Enumeration
Section6.5.Confusion
Section6.6.Methods
Section6.7.Dimensions


Chapter7.RegularExpressions
Section7.1.AnExample

Section7.2.Construction
Section7.3.Elements
Chapter8.Methods
Chapter9.Style
Chapter10.BeautifulFeatures
AppendixA.AwfulParts
SectionA.1.GlobalVariables
SectionA.2.Scope
SectionA.3.SemicolonInsertion
SectionA.4.ReservedWords
SectionA.5.Unicode
SectionA.6.typeof
SectionA.7.parseInt
SectionA.8.+
SectionA.9.FloatingPoint
SectionA.10.NaN
SectionA.11.PhonyArrays
SectionA.12.FalsyValues
SectionA.13.hasOwnProperty
SectionA.14.Object
AppendixB.BadParts
SectionB.1.==
SectionB.2.withStatement
SectionB.3.eval
SectionB.4.continueStatement
SectionB.5.switchFallThrough
SectionB.6.Block-lessStatements
SectionB.7.++-SectionB.8.BitwiseOperators



SectionB.9.ThefunctionStatementVersusthefunction
Expression
SectionB.10.TypedWrappers
SectionB.11.new
SectionB.12.void
AppendixC.JSLint
SectionC.1.UndefinedVariablesandFunctions
SectionC.2.Members
SectionC.3.Options
SectionC.4.Semicolon
SectionC.5.LineBreaking
SectionC.6.Comma
SectionC.7.RequiredBlocks
SectionC.8.ForbiddenBlocks
SectionC.9.ExpressionStatements
SectionC.10.forinStatement
SectionC.11.switchStatement
SectionC.12.varStatement
SectionC.13.withStatement
SectionC.14.=
SectionC.15.==and!=
SectionC.16.Labels
SectionC.17.UnreachableCode
SectionC.18.ConfusingPlusesandMinuses
SectionC.19.++and-SectionC.20.BitwiseOperators
SectionC.21.evalIsEvil
SectionC.22.void
SectionC.23.RegularExpressions
SectionC.24.Constructorsandnew
SectionC.25.NotLookedFor

SectionC.26.HTML


SectionC.27.JSON
SectionC.28.Report
AppendixD.SyntaxDiagrams
AppendixE.JSON
SectionE.1.JSONSyntax
SectionE.2.UsingJSONSecurely
SectionE.3.AJSONParser
Colophon
Index


JavaScript:TheGoodParts
byDouglasCrockford
Copyright©2008Yahoo!Inc.Allrightsreserved.Printedinthe
UnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or

Editor:

SimonSt.Laurent

ProductionEditor:


SumitaMukherji

Copyeditor:

Genevieved'Entremont

Proofreader:

SumitaMukherji

Indexer:

JulieHawks

CoverDesigner:

KarenMontgomery

InteriorDesigner:

DavidFutato

Illustrator:

RobertRomano

PrintingHistory:
May2008:


FirstEdition.

NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
JavaScript:TheGoodParts,theimageofaPlainTigerbutterfly,


andrelatedtradedressaretrademarksofO'ReillyMedia,Inc.
Java™isatrademarkofSunMicrosystems,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ThisbookusesRepKover™,adurableandflexiblelay-flat
binding.
ISBN:978-0-596-51774-8
[M]


Dedication
FortheLads:Clement,Philbert,Seymore,Stern,and,lestwe
forget,C.Twildo.


Preface

Ifweoffend,itiswithourgoodwillThatyoushouldthink,
wecomenottooffend,Butwithgoodwill.Toshowour
simpleskill,Thatisthetruebeginningofourend.
—WilliamShakespeare,AMidsummerNight'sDream
ThisisabookabouttheJavaScriptprogramminglanguage.Itis
intendedforprogrammerswho,byhappenstanceorcuriosity,
areventuringintoJavaScriptforthefirsttime.Itisalso
intendedforprogrammerswhohavebeenworkingwith
JavaScriptatanovicelevelandarenowreadyforamore
sophisticatedrelationshipwiththelanguage.JavaScriptisa
surprisinglypowerfullanguage.Itsunconventionalitypresents
somechallenges,butbeingasmalllanguage,itiseasily
mastered.
MygoalhereistohelpyoutolearntothinkinJavaScript.Iwill
showyouthecomponentsofthelanguageandstartyouonthe
processofdiscoveringthewaysthosecomponentscanbeput
together.Thisisnotareferencebook.Itisnotexhaustiveabout
thelanguageanditsquirks.Itdoesn'tcontaineverythingyou'll
everneedtoknow.Thatstuffyoucaneasilyfindonline.
Instead,thisbookjustcontainsthethingsthatarereally
important.
Thisisnotabookforbeginners.SomedayIhopetowritea
JavaScript:TheFirstPartsbook,butthisisnotthatbook.This
isnotabookaboutAjaxorwebprogramming.Thefocusis
exclusivelyonJavaScript,whichisjustoneofthelanguagesthe
webdevelopermustmaster.
Thisisnotabookfordummies.Thisbookissmall,butitis
dense.Thereisalotofmaterialpackedintoit.Don'tbe
discouragedifittakesmultiplereadingstogetit.Yourefforts
willberewarded.



P2.1.ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:
Italic
Indicatesnewterms,URLs,filenames,andfileextensions.

Constantwidth
Indicatescomputercodinginabroadsense.Thisincludes
commands,options,variables,attributes,keys,requests,
functions,methods,types,classes,modules,properties,
parameters,values,objects,events,eventhandlers,XML
andXHTMLtags,macros,andkeywords.

Constantwidthbold
Indicatescommandsorothertextthatshouldbetyped
literallybytheuser.

P2.2.UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission.
Forexample,writingaprogramthatusesseveralchunksof
codefromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.

Weappreciate,butdonotrequire,attribution.Anattribution


usuallyincludesthetitle,author,publisher,andISBN.For
example:"JavaScript:TheGoodPartsbyDouglasCrockford.
Copyright2008Yahoo!Inc.,978-0-596-51774-8."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenhere,feelfreetocontactusat


P2.3.Safari®BooksOnline
WhenyouseeaSafari®BooksOnlineicononthecoverofyour
favoritetechnologybook,thatmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechbooks,
cutandpastecodesamples,downloadchapters,andfindquick
answerswhenyouneedthemostaccurate,currentinformation.
Tryitforfreeat.

P2.4.HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(internationalorlocal)
707-829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,

examples,andanyadditionalinformation.Youcanaccessthis
pageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send


emailto:

Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:
/>
P2.5.Acknowledgments
Iwanttothankthereviewerswhopointedoutmymany
egregiouserrors.Therearefewthingsbetterinlifethanhaving
reallysmartpeoplepointoutyourblunders.Itisevenbetter
whentheydoitbeforeyougopublic.Thankyou,Steve
Souders,BillScott,JulienLeComte,StoyanStefanov,Eric
Miraglia,andElliotteRustyHarold.
IwanttothankthepeopleIworkedwithatElectric
CommunitiesandStateSoftwarewhohelpedmediscoverthat
deepdowntherewasgoodnessinthislanguage,especiallyChip
Morningstar,RandyFarmer,JohnLa,MarkMiller,Scott
Shattuck,andBillEdney.
IwanttothankYahoo!Inc.forgivingmetimetoworkonthis
projectandforbeingsuchagreatplacetowork,andthanksto
allmembersoftheAjaxStrikeForce,pastandpresent.Ialso
wanttothankO'ReillyMedia,Inc.,particularlyMaryTreseler,
SimonSt.Laurent,andSumitaMukherjiformakingthingsgoso
smoothly.
SpecialthankstoProfessorLisaDrakeforallthosethingsshe
does.AndIwanttothanktheguysinECMATC39whoare

strugglingtomakeECMAScriptabetterlanguage.
Finally,thankstoBrendanEich,theworld'smostmisunderstood
programminglanguagedesigner,withoutwhomthisbookwould
nothavebeennecessary.


Chapter1.GoodParts
...settingtheattractionsofmygoodpartsasideIhaveno
othercharms.
—WilliamShakespeare,TheMerryWivesofWindsor
WhenIwasayoungjourneymanprogrammer,Iwouldlearn
abouteveryfeatureofthelanguagesIwasusing,andIwould
attempttouseallofthosefeatureswhenIwrote.Isupposeit
wasawayofshowingoff,andIsupposeitworkedbecauseI
wastheguyyouwenttoifyouwantedtoknowhowtousea
particularfeature.
EventuallyIfiguredoutthatsomeofthosefeaturesweremore
troublethantheywereworth.Someofthemwerepoorly
specified,andsoweremorelikelytocauseportabilityproblems.
Someresultedincodethatwasdifficulttoreadormodify.
Someinducedmetowriteinamannerthatwastootrickyand
error-prone.Andsomeofthosefeaturesweredesignerrors.
Sometimeslanguagedesignersmakemistakes.
Mostprogramminglanguagescontaingoodpartsandbadparts.
IdiscoveredthatIcouldbeabetterprogrammerbyusingonly
thegoodpartsandavoidingthebadparts.Afterall,howcan
youbuildsomethinggoodoutofbadparts?
Itisrarelypossibleforstandardscommitteestoremove
imperfectionsfromalanguagebecausedoingsowouldcause
thebreakageofallofthebadprogramsthatdependonthose

badparts.Theyareusuallypowerlesstodoanythingexcept
heapmorefeaturesontopoftheexistingpileofimperfections.
Andthenewfeaturesdonotalwaysinteractharmoniously,thus
producingmorebadparts.
Butyouhavethepowertodefineyourownsubset.Youcan
writebetterprogramsbyrelyingexclusivelyonthegoodparts.
JavaScriptisalanguagewithmorethanitsshareofbadparts.


Itwentfromnon-existencetoglobaladoptioninanalarmingly
shortperiodoftime.Itneverhadanintervalinthelabwhenit
couldbetriedoutandpolished.ItwentstraightintoNetscape
Navigator2justasitwas,anditwasveryrough.WhenJava™
appletsfailed,JavaScriptbecamethe"LanguageoftheWeb"by
default.JavaScript'spopularityisalmostcompletely
independentofitsqualitiesasaprogramminglanguage.
Fortunately,JavaScripthassomeextraordinarilygoodparts.In
JavaScript,thereisabeautiful,elegant,highlyexpressive
languagethatisburiedunderasteamingpileofgoodintentions
andblunders.ThebestnatureofJavaScriptissoeffectively
hiddenthatformanyyearstheprevailingopinionofJavaScript
wasthatitwasanunsightly,incompetenttoy.Myintentionhere
istoexposethegoodnessinJavaScript,anoutstanding,
dynamicprogramminglanguage.JavaScriptisablockof
marble,andIchipawaythefeaturesthatarenotbeautifuluntil
thelanguage'struenaturerevealsitself.Ibelievethatthe
elegantsubsetIcarvedoutisvastlysuperiortothelanguageas
awhole,beingmorereliable,readable,andmaintainable.
Thisbookwillnotattempttofullydescribethelanguage.
Instead,itwillfocusonthegoodpartswithoccasionalwarnings

toavoidthebad.Thesubsetthatwillbedescribedherecanbe
usedtoconstructreliable,readableprogramssmallandlarge.
Byfocusingonjustthegoodparts,wecanreducelearning
time,increaserobustness,andsavesometrees.
Perhapsthegreatestbenefitofstudyingthegoodpartsisthat
youcanavoidtheneedtounlearnthebadparts.Unlearning
badpatternsisverydifficult.Itisapainfultaskthatmostofus
facewithextremereluctance.Sometimeslanguagesare
subsettedtomakethemworkbetterforstudents.Butinthis
case,IamsubsettingJavaScripttomakeitworkbetterfor
professionals.

1.1.WhyJavaScript?
JavaScriptisanimportantlanguagebecauseitisthelanguage


ofthewebbrowser.Itsassociationwiththebrowsermakesit
oneofthemostpopularprogramminglanguagesintheworld.
Atthesametime,itisoneofthemostdespisedprogramming
languagesintheworld.TheAPIofthebrowser,theDocument
ObjectModel(DOM)isquiteawful,andJavaScriptisunfairly
blamed.TheDOMwouldbepainfultoworkwithinany
language.TheDOMispoorlyspecifiedandinconsistently
implemented.ThisbooktouchesonlyverylightlyontheDOM.I
thinkwritingaGoodPartsbookabouttheDOMwouldbe
extremelychallenging.
JavaScriptismostdespisedbecauseitisn'tSOMEOTHER
LANGUAGE.IfyouaregoodinSOMEOTHERLANGUAGEand
youhavetoprograminanenvironmentthatonlysupports
JavaScript,thenyouareforcedtouseJavaScript,andthatis

annoying.Mostpeopleinthatsituationdon'tevenbotherto
learnJavaScriptfirst,andthentheyaresurprisedwhen
JavaScriptturnsouttohavesignificantdifferencesfromthe
SOMEOTHERLANGUAGEtheywouldratherbeusing,andthat
thosedifferencesmatter.
TheamazingthingaboutJavaScriptisthatitispossibletoget
workdonewithitwithoutknowingmuchaboutthelanguage,or
evenknowingmuchaboutprogramming.Itisalanguagewith
enormousexpressivepower.Itisevenbetterwhenyouknow
whatyou'redoing.Programmingisdifficultbusiness.Itshould
neverbeundertakeninignorance.


Chapter1.GoodParts
...settingtheattractionsofmygoodpartsasideIhaveno
othercharms.
—WilliamShakespeare,TheMerryWivesofWindsor
WhenIwasayoungjourneymanprogrammer,Iwouldlearn
abouteveryfeatureofthelanguagesIwasusing,andIwould
attempttouseallofthosefeatureswhenIwrote.Isupposeit
wasawayofshowingoff,andIsupposeitworkedbecauseI
wastheguyyouwenttoifyouwantedtoknowhowtousea
particularfeature.
EventuallyIfiguredoutthatsomeofthosefeaturesweremore
troublethantheywereworth.Someofthemwerepoorly
specified,andsoweremorelikelytocauseportabilityproblems.
Someresultedincodethatwasdifficulttoreadormodify.
Someinducedmetowriteinamannerthatwastootrickyand
error-prone.Andsomeofthosefeaturesweredesignerrors.
Sometimeslanguagedesignersmakemistakes.

Mostprogramminglanguagescontaingoodpartsandbadparts.
IdiscoveredthatIcouldbeabetterprogrammerbyusingonly
thegoodpartsandavoidingthebadparts.Afterall,howcan
youbuildsomethinggoodoutofbadparts?
Itisrarelypossibleforstandardscommitteestoremove
imperfectionsfromalanguagebecausedoingsowouldcause
thebreakageofallofthebadprogramsthatdependonthose
badparts.Theyareusuallypowerlesstodoanythingexcept
heapmorefeaturesontopoftheexistingpileofimperfections.
Andthenewfeaturesdonotalwaysinteractharmoniously,thus
producingmorebadparts.
Butyouhavethepowertodefineyourownsubset.Youcan
writebetterprogramsbyrelyingexclusivelyonthegoodparts.
JavaScriptisalanguagewithmorethanitsshareofbadparts.


Itwentfromnon-existencetoglobaladoptioninanalarmingly
shortperiodoftime.Itneverhadanintervalinthelabwhenit
couldbetriedoutandpolished.ItwentstraightintoNetscape
Navigator2justasitwas,anditwasveryrough.WhenJava™
appletsfailed,JavaScriptbecamethe"LanguageoftheWeb"by
default.JavaScript'spopularityisalmostcompletely
independentofitsqualitiesasaprogramminglanguage.
Fortunately,JavaScripthassomeextraordinarilygoodparts.In
JavaScript,thereisabeautiful,elegant,highlyexpressive
languagethatisburiedunderasteamingpileofgoodintentions
andblunders.ThebestnatureofJavaScriptissoeffectively
hiddenthatformanyyearstheprevailingopinionofJavaScript
wasthatitwasanunsightly,incompetenttoy.Myintentionhere
istoexposethegoodnessinJavaScript,anoutstanding,

dynamicprogramminglanguage.JavaScriptisablockof
marble,andIchipawaythefeaturesthatarenotbeautifuluntil
thelanguage'struenaturerevealsitself.Ibelievethatthe
elegantsubsetIcarvedoutisvastlysuperiortothelanguageas
awhole,beingmorereliable,readable,andmaintainable.
Thisbookwillnotattempttofullydescribethelanguage.
Instead,itwillfocusonthegoodpartswithoccasionalwarnings
toavoidthebad.Thesubsetthatwillbedescribedherecanbe
usedtoconstructreliable,readableprogramssmallandlarge.
Byfocusingonjustthegoodparts,wecanreducelearning
time,increaserobustness,andsavesometrees.
Perhapsthegreatestbenefitofstudyingthegoodpartsisthat
youcanavoidtheneedtounlearnthebadparts.Unlearning
badpatternsisverydifficult.Itisapainfultaskthatmostofus
facewithextremereluctance.Sometimeslanguagesare
subsettedtomakethemworkbetterforstudents.Butinthis
case,IamsubsettingJavaScripttomakeitworkbetterfor
professionals.

1.1.WhyJavaScript?
JavaScriptisanimportantlanguagebecauseitisthelanguage


ofthewebbrowser.Itsassociationwiththebrowsermakesit
oneofthemostpopularprogramminglanguagesintheworld.
Atthesametime,itisoneofthemostdespisedprogramming
languagesintheworld.TheAPIofthebrowser,theDocument
ObjectModel(DOM)isquiteawful,andJavaScriptisunfairly
blamed.TheDOMwouldbepainfultoworkwithinany
language.TheDOMispoorlyspecifiedandinconsistently

implemented.ThisbooktouchesonlyverylightlyontheDOM.I
thinkwritingaGoodPartsbookabouttheDOMwouldbe
extremelychallenging.
JavaScriptismostdespisedbecauseitisn'tSOMEOTHER
LANGUAGE.IfyouaregoodinSOMEOTHERLANGUAGEand
youhavetoprograminanenvironmentthatonlysupports
JavaScript,thenyouareforcedtouseJavaScript,andthatis
annoying.Mostpeopleinthatsituationdon'tevenbotherto
learnJavaScriptfirst,andthentheyaresurprisedwhen
JavaScriptturnsouttohavesignificantdifferencesfromthe
SOMEOTHERLANGUAGEtheywouldratherbeusing,andthat
thosedifferencesmatter.
TheamazingthingaboutJavaScriptisthatitispossibletoget
workdonewithitwithoutknowingmuchaboutthelanguage,or
evenknowingmuchaboutprogramming.Itisalanguagewith
enormousexpressivepower.Itisevenbetterwhenyouknow
whatyou'redoing.Programmingisdifficultbusiness.Itshould
neverbeundertakeninignorance.


1.2.AnalyzingJavaScript
JavaScriptisbuiltonsomeverygoodideasandafewverybad
ones.
Theverygoodideasincludefunctions,loosetyping,dynamic
objects,andanexpressiveobjectliteralnotation.Thebadideas
includeaprogrammingmodelbasedonglobalvariables.
JavaScript'sfunctionsarefirstclassobjectswith(mostly)lexical
scoping.JavaScriptisthefirstlambdalanguagetogo
mainstream.Deepdown,JavaScripthasmoreincommonwith
LispandSchemethanwithJava.ItisLispinC'sclothing.This

makesJavaScriptaremarkablypowerfullanguage.
Thefashioninmostprogramminglanguagestodaydemands
strongtyping.Thetheoryisthatstrongtypingallowsacompiler
todetectalargeclassoferrorsatcompiletime.Thesoonerwe
candetectandrepairerrors,thelesstheycostus.JavaScriptis
alooselytypedlanguage,soJavaScriptcompilersareunableto
detecttypeerrors.Thiscanbealarmingtopeoplewhoare
comingtoJavaScriptfromstronglytypedlanguages.Butit
turnsoutthatstrongtypingdoesnoteliminatetheneedfor
carefultesting.AndIhavefoundinmyworkthatthesortsof
errorsthatstrongtypecheckingfindsarenottheerrorsIworry
about.Ontheotherhand,Ifindloosetypingtobeliberating.I
don'tneedtoformcomplexclasshierarchies.AndIneverhave
tocastorwrestlewiththetypesystemtogetthebehaviorthat
Iwant.
JavaScripthasaverypowerfulobjectliteralnotation.Objects
canbecreatedsimplybylistingtheircomponents.Thisnotation
wastheinspirationforJSON,thepopulardatainterchange
format.(TherewillbemoreaboutJSONinAppendixE.)
AcontroversialfeatureinJavaScriptisprototypalinheritance.
JavaScripthasaclass-freeobjectsysteminwhichobjects
inheritpropertiesdirectlyfromotherobjects.Thisisreally
powerful,butitisunfamiliartoclassicallytrainedprogrammers.


Ifyouattempttoapplyclassicaldesignpatternsdirectlyto
JavaScript,youwillbefrustrated.Butifyoulearntoworkwith
JavaScript'sprototypalnature,youreffortswillberewarded.
JavaScriptismuchmalignedforitschoiceofkeyideas.Forthe
mostpart,though,thosechoicesweregood,ifunusual.But

therewasonechoicethatwasparticularlybad:JavaScript
dependsonglobalvariablesforlinkage.Allofthetop-level
variablesofallcompilationunitsaretossedtogetherina
commonnamespacecalledtheglobalobject.Thisisabadthing
becauseglobalvariablesareevil,andinJavaScripttheyare
fundamental.Fortunately,aswewillsee,JavaScriptalsogives
usthetoolstomitigatethisproblem.
Inafewcases,wecan'tignorethebadparts.Therearesome
unavoidableawfulparts,whichwillbecalledoutastheyoccur.
TheywillalsobesummarizedinAppendixA.Butwewill
succeedinavoidingmostofthebadpartsinthisbook,
summarizingmuchofwhatwasleftoutinAppendixB.Ifyou
wanttolearnmoreaboutthebadpartsandhowtousethem
badly,consultanyotherJavaScriptbook.
ThestandardthatdefinesJavaScript(akaJScript)isthethird
editionofTheECMAScriptProgrammingLanguage,whichis
availablefromThe
languagedescribedinthisbookisapropersubsetof
ECMAScript.Thisbookdoesnotdescribethewholelanguage
becauseitleavesoutthebadparts.Thetreatmenthereisnot
exhaustive.Itavoidstheedgecases.Youshould,too.Thereis
dangerandmiseryattheedges.
AppendixCdescribesaprogrammingtoolcalledJSLint,a
JavaScriptparserthatcananalyzeaJavaScriptprogramand
reportonthebadpartsthatitcontains.JSLintprovidesa
degreeofrigorthatisgenerallylackinginJavaScript
development.Itcangiveyouconfidencethatyourprograms
containonlythegoodparts.



JavaScriptisalanguageofmanycontrasts.Itcontainsmany
errorsandsharpedges,soyoumightwonder,"WhyshouldI
useJavaScript?"Therearetwoanswers.Thefirstisthatyou
don'thaveachoice.TheWebhasbecomeanimportant
platformforapplicationdevelopment,andJavaScriptistheonly
languagethatisfoundinallbrowsers.Itisunfortunatethat
Javafailedinthatenvironment;ifithadn't,therecouldbea
choiceforpeopledesiringastronglytypedclassicallanguage.
ButJavadidfailandJavaScriptisflourishing,sothereis
evidencethatJavaScriptdidsomethingright.
Theotheransweristhat,despiteitsdeficiencies,JavaScriptis
reallygood.Itislightweightandexpressive.Andonceyouget
thehangofit,functionalprogrammingisalotoffun.
Butinordertousethelanguagewell,youmustbewell
informedaboutitslimitations.Iwillpoundonthosewithsome
brutality.Don'tletthatdiscourageyou.Thegoodpartsaregood
enoughtocompensateforthebadparts.


1.3.ASimpleTestingGround
Ifyouhaveawebbrowserandanytexteditor,youhave
everythingyouneedtorunJavaScriptprograms.First,makean
HTMLfilewithanamelikeprogram.html:
<html><body>
<scriptsrc="program.js">
</script></pre></body></html>
Then,makeafileinthesamedirectorywithanamelike
program.js:
document.writeln('Hello,world!');

Next,openyourHTMLfileinyourbrowsertoseetheresult.

Throughoutthebook,amethodmethodisusedtodefinenew
methods.Thisisitsdefinition:
Function.prototype.method=function(name,func){
this.prototype[name]=func;
returnthis;
};

ItwillbeexplainedinChapter4.


Chapter2.Grammar
Iknowitwell:Ireaditinthegrammarlongago.
—WilliamShakespeare,TheTragedyofTitusAndronicus
Thischapterintroducesthegrammarofthegoodpartsof
JavaScript,presentingaquickoverviewofhowthelanguageis
structured.Wewillrepresentthegrammarwithrailroad
diagrams.
Therulesforinterpretingthesediagramsaresimple:
Youstartontheleftedgeandfollowthetrackstotheright
edge.
Asyougo,youwillencounterliteralsinovals,andrulesor
descriptionsinrectangles.
Anysequencethatcanbemadebyfollowingthetracksis
legal.
Anysequencethatcannotbemadebyfollowingthetracks
isnotlegal.
Railroaddiagramswithonebarateachendallow
whitespacetobeinsertedbetweenanypairoftokens.
Railroaddiagramswithtwobarsateachenddonot.
Thegrammarofthegoodpartspresentedinthischapteris

significantlysimplerthanthegrammarofthewholelanguage.

2.1.Whitespace


×