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

Premier press javascript professional projects

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 (3.22 MB, 773 trang )

JavaScriptProfessional
Projects
ISBN:1592000134
byPaul
HatcherandJohn
Gosney
PremierPress©2003(591pages)
Withtheinformationinthis
book,youwilllearnhowto
writenotonlyJavaScriptthat
canstandonitsownwithina
Webpage,butalsohowto
writescriptsthatinteractwith
applicationswritteninother
developmentlanguages.
TableofContents
JavaScriptProfessionalProjects
Introduction
PartI-JavaScriptEssentials

Chapter1
Chapter2
Chapter3
Chapter4
Chapter5
Chapter6
Chapter7
Chapter8
Chapter9

- JavaScriptProgrammingBasics


- SelectionandRepetitionStatements
- ArraysandStrings
- JavaScriptFunctions
- Object-OrientedJavaScript
- JavaScriptEventsandTimers
- TheDocumentObjectModel
- HandlingandValidatingForms
- WindowsandFrames
HandlingWebBrowser,ScreenResolution,andColo
Chapter10 -


DepthDifferences
Chapter11 - Client-SideDataasCookies
Chapter12 - EnsuringJavaScriptSecurity
Chapter13 - HandlingErrorsandDebuggingScripts
PartII-ApplyingYourSkills—TheCenterParkSchoolProject

Chapter14 - ProjectOverview—IntroducingCenterParkSchool
Chapter15 - CreatingaJavaScriptCalendar
Chapter16 - CreatinganOnlineTestorSurvey
Chapter17 - CreatingaClient-SideShoppingCart
Chapter18 - SettingUpaMembers-Only,Password-ProtectedWe
Chapter19 - CreatingHyperlinkedAdRotators
UsingJavaScripttoCreateDynamicHTML(DHTML)
Chapter20 Effects
ProjectWrap-up—CenterParkWebSiteFunctional
Chapter21 Overview
Index
ListofFigures

ListofTables
ListofSidebars


BackCover
JavaScriptProfessionalProjectsisyourkeyto
unlockingthepowerofJavaScript.Explorean
advanced,real-worldprojectthatwillgiveyouthe
toolsyouneedtoimplementJavaScriptintoactual
applicationsasyouworkyourwaythroughthe
developmentofaWebsiteforaschool.Youwillbe
abletousetheskillsthatyoudevelopthroughoutthe
booktomodifytheprojecttofityourreal-world
professionalneeds.
MasterJavaScriptEssentials:BeginyourJavaScript
experiencebylearningfundamentaltechniques,
includingtheessentialsofobject-oriented
programming.Youwilldeveloptheskillsnecessaryto
pullthebasicoperationsofasoftwareapplication
togetherinordertobuildapracticalandviablesitefor
yourorganization.Presentingyouwithasolid
foundation,heauthorscoverJavaScriptsecurity
featuresandoffercodedebuggingtipsandtricks.You
willalsoworkwithspecificJavaScriptfunctionality,
includingfunctions,events,andtimers,andwilllearn
howtomanipulatethedocumentobjectmodel(DOM).
ApplyYourKnowledge:Utilizeyournewskillsetby
developingaWebsiteforaschool,asyouplaytherole
ofdesignconsultant.Youwillgainvaluablereal-world
experienceasyouidentifyyourclient’smajor

functionalityrequirements,thendevelopacomplex,
workingwebsitethatisrichinJavaScriptfeatures.
Integrateformprocessing,members-onlyaccess,
dynamiccalendars,andbuildanonlinestore.Youwill


beabletotesttheessentialskillsthatyoulearnedin
Part1ofthebook.
EnhanceYourDesignSkills:Youwilllearnhowto
combinefunctionalitywitheye-catchingdesignby
integratingfeaturessuchasrotatingbannerads.You
willalsolearnhowtohyperlinkthesebanneradsto
additionalpagesformoreinformation.Throughoutthe
project,youwillenhanceyourskillsindeveloping
attractiveanduser-friendlyfunctionalityforyoursite.
AbouttheAuthors
PaulHatcheriscurrentlyattendingIndianaUniversity
PurdueUniversityIndianapoliswhereheisworking
towardsaComputerSciencedegree.Hestarted
workingintheITfieldatanearlyageandhasagreat
dealofexperiencewithapplicationdevelopmentforthe
Webandotherplatforms.
JohnW.GosneyiscurrentlyDirectorofTechnology
ServicesfortheIndianaUniversitySchoolofDentistry.
Hehasworkedinboththepublishingand
pharmaceuticalindustriesasanapplicationdeveloper,
technicalwriterandtrainingconsultant.Johnwrites
extensivelyonallfacetsoftheITarena,frommarket
analysisandforecaststoguidebooksforapplication
developers.Additionally,heisanassociatefaculty

memberfortheIndianaUniversitySchoolofLiberal
Arts,Indianapolis.JohnreceivedhisB.A.intechnical
writingandpsychobiologyin1992fromPurdue
University.In1996hewasawardedanM.A.inEnglish
fromButlerUniversity.


JavaScriptProfessionalProjects
PaulHatcher
JohnW.Gosney
PremierPress
Copyright©2003PremierPress,adivisionofCourseTechnology.
Allrightsreserved.Nopartofthisbookmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
systemwithoutwrittenpermissionfromPremierPress,exceptforthe
inclusionofbriefquotationsinareview.
ThePremierPresslogoandrelatedtradedressaretrademarksof
PremierPressandmaynotbeusedwithoutwrittenpermission.
JavaScriptisatrademarkofNetscapeCommunicationsCorporation.
Important:PremierPresscannotprovidesoftwaresupport.Please
contacttheappropriatesoftwaremanufacturer'stechnicalsupportlineor
Websiteforassistance.
PremierPressandtheauthorshaveattemptedthroughoutthisbookto
distinguishproprietarytrademarksfromdescriptivetermsbyfollowingthe
capitalizationstyleusedbythemanufacturer.
InformationcontainedinthisbookhasbeenobtainedbyPremierPress
fromsourcesbelievedtobereliable.However,becauseofthepossibility
ofhumanormechanicalerrorbyoursources,PremierPress,orothers,
thePublisherdoesnotguaranteetheaccuracy,adequacy,or

completenessofanyinformationandisnotresponsibleforanyerrorsor
omissionsortheresultsobtainedfromuseofsuchinformation.Readers
shouldbeparticularlyawareofthefactthattheInternetisaneverchangingentity.Somefactsmayhavechangedsincethisbookwentto
press.
1-59200-013-4


LibraryofCongressCatalogCardNumber:2002111222
0304050607BH10987654321
SVP,RetailandStrategicMarketGroup:
AndyShafran
Publisher:
StacyL.Hiquet
SeniorMarketingManager:
SarahO'Donnell
MarketingManager:
HeatherHurley
ManagerofEditorialServices:
HeatherTalbot
AssociateMarketingManager:
KristinEisenzopf
ProjectEditor/CopyEditor:
EstelleManticas
TechnicalReviewer:
MichelleJones
RetailMarketCoordinator:
SarahDubois
InteriorLayout:
ShawnMorningstar
CoverDesigner:

MikeTanamachi
Indexer:
KellyTalbot
Proofreader:


LindaQuigley
PremierPress,adivisionofCourseTechnology
25ThomsonPlace
Boston,MA02210
ToElaine
—P.H
ToMelissa,Genna,GeorgeandJackson
—J.G.
Acknowledgments
PaulHatcherwouldliketothankJohnGosneyformakingthisall
possible,StacyHiquetforkeepingusontrack,MichelleJonesensuring
thatourtechnicalmaterialwascorrect,andEstelleManticasforbringing
italltogether.
JohnGosneywouldliketothankhisco-author,PaulHatcher,forhis
professionalismanddesiretogetthejobdoneright.It'sbeengreatto
workwithyou,Paul!Let'sdoitagainverysoon!Johnwouldalsoliketo
givespecialthankstoEstelleManticasfordoingsuchagreatjobin
keepingtheprojectontrack,andfornotlosinghersenseofhumor,orher
understandingthat"therealworld"sometimesgetsintheway(atleast
forafewdays)ofmeetingdeadlines.ThanksaswelltoStacyHiquetfor
continuingtopresentterrificwritingopportunities.
AbouttheAuthors
PaulHatcheriscurrentlyattendingIndianaUniversityPurdueUniversity
IndianapoliswhereheisworkingtowardsaComputerSciencedegree.

HestartedworkingintheITfieldatanearlyageandhasagreatdealof
experiencewithapplicationdevelopmentfortheWebandother
platforms.
JohnW.GosneyiscurrentlyDirectorofTechnologyServicesforthe
IndianaUniversitySchoolofDentistry.Hehasworkedinboththe


publishingandpharmaceuticalindustriesasanapplicationdeveloper,
technicalwriterandtrainingconsultant.Johnwritesextensivelyonall
facetsoftheITarena,frommarketanalysisandforecaststoguidebooks
forapplicationdevelopers.Additionally,heisanassociatefaculty
memberfortheIndianaUniversitySchoolofLiberalArts,Indianapolis.
JohnreceivedhisB.A.intechnicalwritingandpsychobiologyin1992
fromPurdueUniversity.In1996hewasawardedanM.A.inEnglishfrom
ButlerUniversity.Johnenjoysspendingtimewithhisfamily,cheeringfor
hisfavoriteteams(Pacers,ColtsandBoilermakers)andfurtheringhis
reputationasanexpertinallthingspopularculture.


Introduction
Ifyou'vepurchasedthisbook(orarestandinginthebookstorethinking
aboutpurchasingit),you'veprobablyalreadymadeupyourmindtostart
integratingJavaScriptintoyourWebprojects—oratleastyou're
interestedinthemultifacetedapplicationsyoucanbuildwithit.Thatsaid,
thisbookisnotbeginner-level"basictutorial,"butamoreadvanced
explorationofareal-worldprojectthatwillshowyouhowtoimplement
JavaScriptinactualapplications.Thisbookbeginswheremostother
tutorialsleaveoff—byshowingyouhowtopulltogetherthebasic
operationsofasoftwareapplicationinordertoactuallybuildpracticaland
viableWebsiteforyourorganization.



WhatAretheGoalsofThisBook?
Althoughthisbookisdividedintotwoparts,ithasseveralspecificgoals
inmind.Thosegoalsinclude:
PresentingthefundamentalsofJavaScript.From
programmingbasicstoworkingwithforms,fromlearningabout
JavaScriptsecuritytopresentingyouwithcodedebuggingtips
andtricks,PartI(Chapters1–13)willlaythenecessary
groundworkforboththeprojectcasestudyandyourownspecific
JavaScriptprojects.
Teachinggoodcodingpracticesandfundamental
programmingskills.Itcouldbesaidthatprogrammingall
comesdowntounderstandingsomebasicconcepts.Thatis,if
youknowthefoundationalrules,youcanquicklylearnand
implementnewskills.Withthisinmind,we'vewrittenthe
chaptersofPartItogiveyouthis"ground-levelunderstanding"of
JavaScript.We'veincludedlotsofsamplecodeintheseearly
chapters,sothatasyoulearnaboutthegeneralconcepts,you
canimmediatelyseethempracticallyimplemented.
Developinga"realworld"JavaScript-enabledWebsite.Part
IIofthebookputsyouintheroleofWebdesignerforthefictitious
CenterParkSchool.Ratherthanjustthrowingabunchofsample
codeatyouandaskingyoutomakesenseofitonyourown,the
projectisdividedintochaptersthatdealwithaspecificaspectof
thefinalWebsite.Thefirstprojectchapter(Chapter14)andthe
last(Chapter21)presentyouwithabefore-and-afterprojectview
thatwillincreaseyourlargerunderstandingoftheissuesinvolved
whileworkingwithJavaScriptinanactualapplication.
ExaminingtheentireWebdevelopmentpicture.There'smore

toWebdesignthanjustsimplecode.Indeed,theactualcodingof
aprojectisoftenthe"easy"part,anddevelopingadesignplan
andprojecttemplatetherealchallenge.Workingwithclientscan


beadauntingtask,especiallyifthosecustomersarenot
technicallyminded.Togiveyouasenseofwhatit'sliketoplan
anddevelopanentireWebproject,weaskyoutoimaginethat
youaretheactualdesigneroftheCenterParksite,andto
addresstherequestsputforwardbytheschooladministrators.
Thisbookhasbeenwrittenfromaholistic,totalapplication-solution
perspective.Whileyou'llbepresentedwiththefunctionalfoundationsof
JavaScriptinthechaptersthatcomposePartI,youalsogetachancein
PartIItoexamineaJavaScript-richWebsiteandtostudythecodethat
makesthesitefunction.


WhatIstheProjectCaseStudy?
InPartII,you'llbepresentedwiththeCenterParkSchoolproject,where
you'llbeaskedtobuildafunctional,feature-richWebsiteforthismadeupprivatesecondaryschool.
Byworkingthroughtheproject,youwill:
AddressthelargerdesignissuesofaWebsite.Whilethis
bookisnotaboutprojectmanagement,itwouldbefoolishto
presentyouwitha"real-world"project,andnotaddressthe
processandproceduralplanningissuesthatmustbedealtwithin
thisarena.Again,you'llplaytheroleofWebdesigner,working
withtheschooladministratorstoensurethefinalprojectis
reflectiveoftheirrequirementsforeachspecific"customer"—
parents,teachersandstudents.
BuildonfundamentalJavaScriptskillsfromPartI.InPartI

wetriedtoavoidpresentingyourudimentaryinformationthatyou
havelittlechanceofusingpracticallyinyourownwork.We
wantedtogiveyouthereal-worldtoolsthatyoucouldturnaround
anduseinarealworldprojectliketheCenterParkproject.The
goalhereistoshowyouJavaScript"inaction"andinaformat—
theCenterParkproject—thatisfunctionalandpracticalforyour
study.
Developanunderstandingofhowdifferentfunctional
aspectsofJavaScriptworktogether.Ifyouworkthroughthe
chaptersofPartIinsequentialorder,you'llseehowone
functionalcomponentofJavaScriptintegrateswithanotherto
buildlarger,morecomplex(andinteresting)Webapplications.
TheCenterParkschoolinformationhasbeenpresentedinthe
sameway.Bygraduallybuildingthefunctionalityofthesitefrom
the"groundup,"you'llgettoseealloftheJavaScriptfeatures
cometogethertocreatesomethingfunctional,professional,and
maybeevenexciting!


PartI:JavaScriptEssentials
Chapter1:JavaScriptProgrammingBasics
Chapter2:SelectionandRepetitionStatements
Chapter3:ArraysandStrings
Chapter4:JavaScriptFunctions
Chapter5:Object-OrientedJavaScript
Chapter6:JavaScriptEventsandTimers
Chapter7:TheDocumentObjectModel
Chapter8:HandlingandValidatingForms
Chapter9:WindowsandFrames
Chapter10:HandlingWebBrowser,ScreenResolution,andColor

DepthDifferences
Chapter11:Client-SideDataasCookies
Chapter12:EnsuringJavaScriptSecurity
Chapter13:HandlingErrorsandDebuggingScripts


Chapter1:JavaScriptProgrammingBasics


Overview
JavaScript,designedbyNetscapeCommunicationsandSun
Microsystems,isalightweightprogramminglanguagethatyoucanuseto
adddynamiceffectstoyourWebpages.HTML(HypertextMarkup
Language)canonlydescribethewayaWebpage'selements(text,
forms,hyperlinks,andtables)look—ithasnowayofdictatinghowthey
behave.TheabilitytoembedJavaScriptscriptsinaWebpagegivesyou,
theprogrammer,muchmorecontroloverhowyourWebpagebehaves.
ScriptinglanguageslikeJavaScriptgiveWebpagesfarmoreprocessing
power.JavaScriptallowsaWebpagetointeractwithbothasitevisitor
andtheWebserverfromwhichthepageoriginated.Onecommonuse
forJavaScriptisformvalidation,theprocessbywhichaformischecked
priortosubmissioninordertoverifythatitcontainsalltherequired
informationandthatitisinthecorrectformat.Byitself,HTMLallowsa
visitortoretrieveaformfromaserver,fillintherequiredinformation,and
sendtheformbacktotheserverforprocessing.Unfortunately,iftheuser
entersinvaliddata,thewholeprocessmustberepeateduntilentirely
validdataisentered.AsJavaScriptisexecutedintheclientbrowser,
formvalidationcanoccuraftertheuserhasfilledouttheformandbefore
itissentbacktotheserver.Thissavesboththeclientandserver
considerabletime.

Asyoureadthroughthisbookstudyingtheprojectsandcustomizingthe
codeI'llpresent,bearinmindthatJavaScriptisascriptinglanguagethat
wascreatedtoruninbrowsers.Becauseofthis,JavaScriptcannotbe
usedtocreatestand-aloneprograms,inthesamewaythatHTMLcannot
beusedtocreatestand-aloneprograms.BothJavaScriptandHTML
requireaWebbrowserinordertobeexecuted.Moreprecisely,a
JavaScriptinterpreterisrequiredtounderstandandrunJavaScript
programs.JavaScriptinterpreterscomeprepackagedinalmostallof
today'smainstreamWebbrowsers(includingNetscapeandInternet
Explorer).Thismeansthataclientwillnotneedtoinstallanyother
programsontheircomputersbeforeusingWebsiteswithembedded
JavaScript.


Unlikewithmanyoftoday'scommonprogramminglanguages—suchas
C,C++,VisualBasic,andJava—youdon'tneedanyspecial
developmentenvironmentinordertowriteJavaScriptapplications.You
canusethesametexteditoryou'reusingtocreateyourWebpages.To
insertascriptintoapreexistingWebpage,youneedonlyenclosethe
JavaScriptcodebetweenscripttags(<script>…</script>).Thiswill
telltheWebbrowsertoexecutethecodeinsteadoftryingtodisplayit.As
anexample,hereisasimpleWebpagethatdisplaystheclassicHello
World!!message:
<html>

<head>
<title>
JavaScriptProfessionalProjects-"HelloWorld!!"Exampl
</title>
</head>

<body>

<fontsize=6>JavaScriptProfessionalProjects</font>

<fontsize=4>Chapter1:"HelloWorld!!"Example</font>






NotonlycanyoudisplaytextasusualonyourWebpage,
butyoucanalsouseJavaScript'sbuiltin'document.writ
functiontodisplaydynamicinformationsuchasthecurre
dateandtime.


<scriptlanguage="JavaScript">
newDate().toString()+"
");
//-->
</script>






YoucanalsouseJavaScripttodisplaynormalHTML
elementsrepeatedly.Hereisanexampleofthat:


<scriptlanguage="JavaScript">
{
document.write("HelloWorld!!
");
}

//--<
</script>




Asyoucansee,JavaScripthasgreatpower.


</body>
</html>
Thestatementsenclosedinthescripttagsareconsideredexecutable
codebythebrowser.Itisimportanttospecifythelanguageattribute's
valueforthescripttagbecauseJavaScriptisnottheonlyscripting
languagethatcanbeembeddedwithinWebpages.Inaddition,itis
alwaysagoodideatoincludeHTMLcommenttagswithinthescripttags,
toallowforolderbrowsersthatdonotsupportJavaScript.
Allofthecommandsusedinthecodeexamplejustpresentedwillbe
explainedinfullinthefollowingchapters.Toruntheexample,typethe
HTMLcodeintoatexteditor(suchasNotepadforWindows,VIforUnix,
orApplescriptforMac)andsaveitasHelloWorld.html.Openingthefilein
yourbrowserwilldisplaythepagethatyouseeinFigure1.1.



Figure1.1:ApagedisplayingsimpleJavaScript
capabilities.
WhenJavaScriptcodeisembeddedintoanHTMLWebpage,the
browserwillreadanddisplaytheHTMLasusual.Whenthebrowser
encountersascripttag,itwillinterprettheJavaScriptcode.The
JavaScriptcodecanthenbeexecutedasthepageloads,theentiretime
thepageisbeingdisplayed,asthepageisbeingunloaded,oralongwith
programmer-designatedevents.Itisimportanttorememberthatthe

interpretationoccursattheclientsideandaftertheWebpagehasbeen
completelydownloadedfromtheserver.Thishasitsadvantagesand
disadvantages.BecauseJavaScriptisrunontheclient'scomputer,itis
unabletoaccessresourceslocatedontheserverfromwhichitoriginated
—mostnotablearedatabases.JavaScriptdoes,however,runmuch
fasterthanotherserver-sidelanguagesthatdocommunicateddirectly
withtheserver.Whenusedincombinationwiththebrowser'sDocument
ObjectModel(DOM),JavaScriptcanproduceintricate,dynamicHTML
effectsaswellasanimationandsound.


LexicalDefinition
Thelexicaldefinitionofalanguageissimplythewordsthatareusedto
writestatementsinthatlanguage.InthecaseofJavaScript,thelexical
definitionisborrowedinlargepartfromlanguagessuchasC,C++,and
Java.Theselanguages,andJavaScript,havethreebasictypesof
statementsor"words,"thatmakeupthelanguage:assignment
statements,selectionstatements,anditerativestatements.
Assignmentstatementsmakeupamajorityoftheprogramsource.This
typeofstatementincludesvariabledeclaration,classdefinition,anduserdefinedfunctions.Selectionstatementsprovideawaytochoosebetween
twoormoreexecutionpathsinaprogram.Iterativestatementsprovidea
wayforablockofcodetobeexecutedzeroormoretimesconsecutively.
Assignmentstatementsarecoveredlaterinthischapter,andselection
andrepetitionstatementsarecoveredinChapter2,"Selectionand
RepetitionStatements."
Inadditiontospecifyingthewordsthatmakeupthelanguage,thelexical
definitionofalanguagealsospecifieshowaprogrammercanname
variablesandtowhatformatliteraldefinitionsmustconform.In
JavaScript,theidentifiersusedtonamevariablesmustfollowseveral
rules;I'llexplaintheserulesinthefollowingsection.LiteralsinJavaScript

consistofstringsandnumbers.Stringsarealwaysenclosedinquotation
marks(eithersingle'ordouble'')andnumbersarenot.

JavaScriptIdentifiers
MostoftheJavaScriptstatementsyouwritewillrequestdatafromthe
clientWebbrowserorfromtheserverfromwhichtheWebpage
originated.Inorderforthatdatatobeuseful,youneedaplacetostoreit.
Tofacilitatethestorageofdata,JavaScriptgivesyoutheabilitytodeclare
variablestostoreandtosymbolicallyusethedata.Eachvariablethatis
declaredwillhaveaname,oridentifier,thatallowsthedatatobereferred
toeasily.ExamplesofidentifiersthatmightbeusedinJavaScriptare:
counter,userName,andlistItem97.
Whencreatinganidentifier,youshouldrememberthefollowingvery


importantguidelines:
ThefirstcharacterofanidentifiermustbeanASCIIletter,an
underscore(_),oradollarsign($).
Anidentifiermustneverbeginwithanumber.
AnidentifiermustneverconsistentirelyofJavaScriptreserved
words.AcompletelistofJavaScript'sreservedwordscanbe
foundlaterinthischapter.
JavaScriptisacase-sensitivelanguage,andso,forexample,
casetest,CaseTest,andcaseTestcanallbeused
simultaneouslybecausetheyareconsidereddifferentidentifiers
bytheinterpreter.
Identifiersareusednotonlytonamevariables,butalsotoidentifyuserdefinedfunctionsandclasses.Carefulselectionofidentifiernameswill
helppromotereadabilityandhelpwithfuturecodemaintenance.See
Table1.1forashortlistofidentifiersandtheirdescriptions.
Table1.1:BadandGoodIdentifiers

BadIdentifier Reason

GoodIdentifier

7th_element Beginswithnumber.

element_7

@address

Doesnotbeginwith_,$,orletter.

address

in

IsaJavaScriptreservedword.

Input

Followingisasimpleexamplethatdemonstratesdeclaringvariablesand
JavaScriptcase-sensitivity:
<html>
<head>
<title>


JavaScriptProfessionalProjects-Identifiersandlitera
</title>
<scriptlanguage="JavaScript">


</script>
</head>
<body>

<fontsize=6>JavaScriptProfessionalProjects</font>

<fontsize=4>Chapter1:Identifiersandliterals</font>






Thevalueof<fontface="CourierNew">casetest</font>is:<
<scriptlanguage="JavaScript">

</script>
"</b>.Itwasinitializedtothatstringliteralwhen
itwasdeclared.




Thevalueof<fontface="CourierNew">CaseTest</font>is:<
<scriptlanguage="JavaScript">



//-->
</script>
</b>.Itwasinitializedtothatnumberliteralwhen
itwasdeclared.




Thevalueof<fontface="CourierNew">caseTest</font>is:<
<scriptlanguage="JavaScript">

</script>
</b>.Itwasnotinitializedwithaliteralatall.
Insteaditwasdeclaredasadateobject.


</body>
</html>
Inthisexample,threevariables—casetest,CaseTest,andcaseTest
(noticethedifferentcapitalization)—aredeclared,andeachisassigneda
differentvalue.casetestwasassignedastringvalue,CaseTestwas
assignedanintegervalue,andcaseTestwasdeclaredasaDate
object.Inthebodyofthepage,eachvariableisusedinordertoshowthe
lackofambiguityofJavaScript'scase-sensitivedesign.

JavaScriptLiterals
Aliteralisdatathathasbeenentereddirectlyintothesourcecodeofa
program.Someexamplesofliteralsare42,3.14,and"Onceupona
time".Literalsarecommonlyusedtoinitializethevalueofavariable.
Forexample,ifaloopusesacounter,itmightbedeclaredasfollows:
varcounter=0;Thenamecounterisanidentifierandthenameof

thevariable,while0isaliteralandtheinitialvalueofcounter.Literals
canbeusedtoinitializevariablestoanumber,boolean,orstringvalue.


ReservedKeyWords
JavaScript,likealmostallprogramminglanguages,hasalistofreserved
wordsthatareuseddirectlybythelanguageitselfand,consequently,
cannotbeusedasvariablenames.Keywords,orlexemes,makeupthe
lexicaldefinitionofalanguage.AcompletelistofJavaScript'sreserved
wordsisasfollows:
abstract

boolean break

byte

case

char

class

const

continue

debugger default

delete


do

double else

enum

export

extends

false

final

finally

float

for

function

goto

if

implements import

instanceof int


interface long

null

package private protected

short

static

throws

transient true

void

while

switch
with

catch

in

native

new

public


return

synchronized this

throw

try


var


typeof


ThelistofreservedwordsmakesupthevocabularyoftheJavaScript
language.Bycombiningthesewordsinvariousways,thefullpowerof
thelanguageisrealized.
Althoughitispossibletousethereservedwordsasidentifiersifyougive
themdifferentcapitalization,itisstronglydiscouragedbecauseit
hampersreadability,asyoucanseeinthefollowingexample:
varVar=9>=7;
varTrue=false;
varIf=Var&&True;
if(If)
{
document.write("Thisisveryconfusing.");
}



Clearly,usingkeywordsinanyformcanleadtounreadablecode.

Comments
Commentsareaveryhelpfulfeatureofeveryprogramminglanguage.
Addingcommentsallowsafuturereaderofyoursourcecodeto
understandwhatyouwerethinkingwhenyouwrotethecode.
TherearetwotypesofcommentsinJavaScript,blockcommentsandline
comments.Blockcommentsarestartedbya/*symbolandterminatedby
a*/.Alltextinbetweenthesetwosymbolswillbeignoredbythe
browser'sinterpreter.Blockcommentsareusefulwhenyouneedtoleave
alongercomment,suchasaprogramheaderordescriptionofuserdefinedfunctions.Linecommentsareprecededbythe//symboland
havenoterminatorsymbol.Linecommentsendatthenextlinebreak
andareusefulfordescribingtheuseofvariables,leavingquicknoteson
programflowwithinfunctions,andfordebuggingpurposes.
Followingisanexampleshowingbothtypesofcomments:
<html>
<head>
<title>
JavaScriptProfessionalProjects-Comments
</title>
<scriptlanguage="JavaScript">
Thisisablockcomment.Youshouldplacethese
beforeeachfunctionyouwritetogivethereader
anideaofwhatitdoes.
Alltextinthistypeofcommentisignoredbythe
interpreter-includingJavaScriptcommands!
*/
functionprototype()



{
//Thisisaonelinecomment
//Thesecommentsareusedtoexplainkeysteps
//withinafunction.
}
//-->
</script>
</head>
<body>

<fontsize=6>JavaScriptProfessionalProjects</font>

<fontsize=4>Chapter1:Comments</font>

</body>
</html>
Itisagoodideatogetinthehabitofusingcommentsthroughouta
programduringthecodingprocess.Theresultofusingcommentswillbe
aprofessional-lookingandeasy-to-maintainsourceprogram.

WhiteSpaceandLineBreaks
Thebrowserignoresallwhitespace—includingnormalspaces,tabs,and
linebreaks,—duringinterpretation.Theonlyexceptiontothatruleis
whitespacethatispartofaliteral.Whitespaceisusedpurelyfor
aestheticreasons,buteventhoughwhitespacehasnodirecteffecton
theexecutionofaprogram,itisstillveryimportant.Awell-formatted
sourcefilewilldrasticallyincreasethereadabilityofaprogramandmake
maintainingitmuchlessofachore.
Followingisanexampleofcodewithoutenoughwhite

space:


×