Tải bản đầy đủ - 0 (trang)
Chapter 4. JavaScript: Introduction to Scripting

Chapter 4. JavaScript: Introduction to Scripting

Tải bản đầy đủ - 0trang

4.1 Introduction

4.2 SimpleProgram:DisplayingaLineofTextinaWeb

Page

4.3 ModifyingOurFirstProgram

4.4 ObtainingUserInputwithpromptDialogs





4.4.1 DynamicWelcomePage







4.4.2 AddingIntegers



4.5 DataTypesinJavaScript

4.6 Arithmetic

4.7 DecisionMaking:EqualityandRelationalOperators

4.8 WebResources



4.1.Introduction

Inthefirstthreechapters,weintroducedWeb2.0,XHTMLand

CascadingStyleSheets(CSS).Inthischapter,webeginour

introductiontotheJavaScript[1]scriptinglanguage,which

facilitatesadisciplinedapproachtodesigningcomputer

programsthatenhancethefunctionalityandappearanceofweb

pages.[2]

[1]ManypeopleconfusethescriptinglanguageJavaScriptwiththe



programminglanguageJava(fromSunMicrosystems,Inc.).Javaisafullfledgedobject-orientedprogramminglanguage.Itcanbeusedtodevelop

applicationsthatexecuteonarangeofdevices—fromthesmallestdevices

(suchascellphonesandPDAs)tosupercomputers.Javaispopularfor

developinglarge-scaledistributedenterpriseapplicationsandwebapplications.

JavaScriptisabrowser-basedscriptinglanguagedevelopedbyNetscapeand

implementedinallmajorbrowsers.

[2]JavaScriptwasoriginallycreatedbyNetscape.BothNetscapeandMicrosoft



havebeeninstrumentalinthestandardizationofJavaScriptbyECMA

InternationalasECMAScript.DetailedinformationaboutthecurrentECMAScript

standardcanbefoundatwww.ecmainternational.org/publications/standards/ECMA-262.htm.



Chapters4–9presentadetaileddiscussionofJavaScript—the

defactostandardclient-sidescriptinglanguageforweb-based

applications,duetoitshighlyportablenature.Ourtreatmentof

JavaScriptservestwopurposes—itintroducesclient-side

scripting(usedinChapters4–11),whichmakeswebpages

moredynamicandinteractive,anditprovidesthefoundation

fortheserver-sidescriptingpresentedlaterinthebook.

WenowintroduceJavaScriptprogrammingandpresent

examplesthatillustrateseveralimportantfeaturesof

JavaScript.Eachexampleiscarefullyanalyzedonelineata

time.InChapters5–6,wepresentadetailedtreatmentof

programdevelopmentandprogramcontrolinJavaScript.

BeforeyoucanruncodeexampleswithJavaScriptonyour

computer,youmayneedtochangeyourbrowser'ssecurity

settings.Bydefault,InternetExplorer7preventsscriptson

yourlocalcomputerfromrunning,displayingayellowwarning

baratthetopofthewindowinstead.Toallowscriptstorunin

filesonyourcomputer,selectInternetOptionsfromtheTools

menu.ClicktheAdvancedtabandscrolldowntotheSecurity

sectionoftheSettingslist.ChecktheboxlabeledAllowactive

contenttoruninfilesonMyComputer(Fig.4.1).ClickOKand

restartInternetExplorer.XHTMLdocumentsonyourown

computerthatcontainJavaScriptcodewillnowrunproperly.

FirefoxhasJavaScriptenabledbydefault.

Figure4.1.EnablingJavaScriptinInternetExplorer7



4.JavaScript:IntroductiontoScripting

Objectives

Inthischapteryouwilllearn:

TowritesimpleJavaScriptprograms.

Touseinputandoutputstatements.

Basicmemoryconcepts.

Tousearithmeticoperators.

Theprecedenceofarithmeticoperators.

Towritedecision-makingstatements.

Touserelationalandequalityoperators.

Commentisfree,butfactsaresacred.

—C.P.Scott

Thecreditorhathabettermemorythanthedebtor.

—JamesHowell

Whenfacedwithadecision,Ialwaysask,"What

wouldbethemostfun?"

—PeggyWalker

Equality,inasocialsense,maybedividedintothatof

conditionandthatofrights.

—JamesFenimoreCooper

Outline



4.1 Introduction

4.2 SimpleProgram:DisplayingaLineofTextinaWeb

Page

4.3 ModifyingOurFirstProgram

4.4 ObtainingUserInputwithpromptDialogs





4.4.1 DynamicWelcomePage







4.4.2 AddingIntegers



4.5 DataTypesinJavaScript

4.6 Arithmetic

4.7 DecisionMaking:EqualityandRelationalOperators

4.8 WebResources



4.1.Introduction

Inthefirstthreechapters,weintroducedWeb2.0,XHTMLand

CascadingStyleSheets(CSS).Inthischapter,webeginour

introductiontotheJavaScript[1]scriptinglanguage,which

facilitatesadisciplinedapproachtodesigningcomputer

programsthatenhancethefunctionalityandappearanceofweb

pages.[2]

[1]ManypeopleconfusethescriptinglanguageJavaScriptwiththe



programminglanguageJava(fromSunMicrosystems,Inc.).Javaisafullfledgedobject-orientedprogramminglanguage.Itcanbeusedtodevelop

applicationsthatexecuteonarangeofdevices—fromthesmallestdevices

(suchascellphonesandPDAs)tosupercomputers.Javaispopularfor

developinglarge-scaledistributedenterpriseapplicationsandwebapplications.

JavaScriptisabrowser-basedscriptinglanguagedevelopedbyNetscapeand

implementedinallmajorbrowsers.

[2]JavaScriptwasoriginallycreatedbyNetscape.BothNetscapeandMicrosoft



havebeeninstrumentalinthestandardizationofJavaScriptbyECMA

InternationalasECMAScript.DetailedinformationaboutthecurrentECMAScript

standardcanbefoundatwww.ecmainternational.org/publications/standards/ECMA-262.htm.



Chapters4–9presentadetaileddiscussionofJavaScript—the

defactostandardclient-sidescriptinglanguageforweb-based

applications,duetoitshighlyportablenature.Ourtreatmentof

JavaScriptservestwopurposes—itintroducesclient-side

scripting(usedinChapters4–11),whichmakeswebpages

moredynamicandinteractive,anditprovidesthefoundation

fortheserver-sidescriptingpresentedlaterinthebook.

WenowintroduceJavaScriptprogrammingandpresent

examplesthatillustrateseveralimportantfeaturesof

JavaScript.Eachexampleiscarefullyanalyzedonelineata

time.InChapters5–6,wepresentadetailedtreatmentof

programdevelopmentandprogramcontrolinJavaScript.

BeforeyoucanruncodeexampleswithJavaScriptonyour

computer,youmayneedtochangeyourbrowser'ssecurity

settings.Bydefault,InternetExplorer7preventsscriptson

yourlocalcomputerfromrunning,displayingayellowwarning

baratthetopofthewindowinstead.Toallowscriptstorunin

filesonyourcomputer,selectInternetOptionsfromtheTools

menu.ClicktheAdvancedtabandscrolldowntotheSecurity

sectionoftheSettingslist.ChecktheboxlabeledAllowactive

contenttoruninfilesonMyComputer(Fig.4.1).ClickOKand

restartInternetExplorer.XHTMLdocumentsonyourown

computerthatcontainJavaScriptcodewillnowrunproperly.

FirefoxhasJavaScriptenabledbydefault.

Figure4.1.EnablingJavaScriptinInternetExplorer7



4.2.SimpleProgram:DisplayingaLine

ofTextinaWebPage

JavaScriptusesnotationsthatarefamiliartoprogrammers.We

beginbyconsideringasimplescript(orprogram)that

displaysthetext"WelcometoJavaScriptProgramming!"in

thebodyofanXHTMLdocument.Allmajorwebbrowsers

containJavaScriptinterpreters,whichprocessthecommands

writteninJavaScript.TheJavaScriptcodeanditsoutputin

InternetExplorerareshowninFig.4.2.

Figure4.2.Displayingalineoftext.



1

2
3"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"

4

5

6

7

8

9AFirstPrograminJavaScript

10

11

15

16

17

[Viewfullsizeimage]



ThisprogramillustratesseveralimportantJavaScriptfeatures.

WeconsidereachlineoftheXHTMLdocumentandscriptin

detail.Asintheprecedingchapters,wehavegiveneachXHTML

documentlinenumbersforyourconvenience;thelinenumbers

arenotpartoftheXHTMLdocumentoroftheJavaScript

programs.Lines12–13dothe"realwork"ofthescript,namely,

displayingthephraseWelcometoJavaScriptProgramming!

inthewebpage.

Line8indicatesthebeginningofthesectionofthe

XHTMLdocument.Forthemoment,theJavaScriptcodewe

writewillappearinthesection.Thebrowserinterprets

thecontentsofthesectionfirst,sotheJavaScript

programswewritethereexecutebeforetheofthe

XHTMLdocumentdisplays.InlaterchaptersonJavaScriptand

inthechaptersondynamicHTML,weillustrateinline

scripting,inwhichJavaScriptcodeiswrittenintheof

anXHTMLdocument.

Line10usesthe



Whenabrowserthatdoesnotsupportscriptsencountersthe

precedingcode,itignoresthetags

andthescriptcodeintheXHTMLcomment.Browsersthatdo

supportscriptingwillinterprettheJavaScriptcodeasexpected.

[Note:SomebrowsersrequiretheJavaScriptsingle-line

comment//(seeSection4.4foranexplanation)beforethe

endingXHTMLcommentdelimiter(-->)tointerpretthescript

properly.TheopeningHTMLcommenttag()is

precededbyaJavaScriptcomment(//)to



preventthebrowserfromtryingto

interprettheXHTMLcommentasa

JavaScriptstatement.



Lines12–13instructthebrowser'sJavaScriptinterpreterto

performanaction,namely,todisplayinthewebpagethe

stringofcharacterscontainedbetweenthedoublequotation

(")marks.Astringissometimescalledacharacterstring,a

messageorastringliteral.Werefertocharactersbetween

doublequotationmarksasstrings.Individualwhite-space

charactersbetweenwordsinastringarenotignoredbythe

browser.However,ifconsecutivespacesappearinastring,

browserscondensethemtoasinglespace.Also,inmostcases,

browsersignoreleadingwhite-spacecharacters(i.e.,white

spaceatthebeginningofastring).

SoftwareEngineeringObservation4.1

StringsinJavaScriptcanbeenclosedin

eitherdoublequotationmarks(")orsingle

quotationmarks(').



Lines12–13usethebrowser'sdocumentobject,which

representstheXHTMLdocumentthebrowseriscurrently

displaying.Thedocumentobjectallowsyoutospecifytextto

displayintheXHTMLdocument.Thebrowsercontainsa

completesetofobjectsthatallowscriptprogrammerstoaccess

andmanipulateeveryelementofanXHTMLdocument.Inlater

chapters,weoverviewsomeoftheseobjectsaswediscussthe

DocumentObjectModel(DOM).



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4. JavaScript: Introduction to Scripting

Tải bản đầy đủ ngay(0 tr)

×