Sunteți pe pagina 1din 13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
Thebestfreecertificationstudyguides,practicetestsandforums!

JoinUs!|Login|Help

SEARCH
Home|ExamDetails|FreeTests|StudyGuides|Glossary|Articles|Books&Training|Forums|Career&Jobs
Certifications
Microsoft
CompTIA
Cisco
CIW
LPI
RedHat
IBM
SiteTools
FreeMagazines
WhitePapers
TopSites
Contributors
SiteMap
FAQ

PracticeTests

ForumStats
Usersonline
totalusers:185
LastPost
HangHuangrailway
management
behavior
standardization
byzhangxiaosan
Sep.27,201622:57
Boardstatistics
Wehaveatotalof
95116posts!

Links
TechTutorials
CertifyPro
Certnotes
A+Tutorials

Sponsor

CIWJavaScriptStudyGuide
TutorialQuickLinks:

IntroductiontoJavascript
WorkingWithVariablesandData
Functions,Methods,andEvents
ControllingProgramFlow
TheJavaScriptObjectModel
LanguageObjects
InteractiveForms
CookiesandJavaScriptSecurity
ControllingFramesinJavaScript
ClientSideJavaScript
CustomJavaScriptObjects

TrainingPicks
EDULEARN

IntroductiontoJavaScript
NetscapeCorporationoriginallydevelopedJavaScript.OriginallynamedLiveScript,Netscapechangedthenameto
JavaScriptinordertoutilizeJava'snamerecognition.ServerSideJavaScriptisknownasLiveWire.Itisstoredand
executedontheservermachine.
ThereareCurrently5versionsofJS1.0,1.1,1.2,1.3,and1.4.FirstsupportedinNavigatorversion2.0,Internet
Explorerversion3.0,Moasaic2.0andLotusPersonalWebClient3.0.
JavaScript,alanguageofobjects,isnotcompiledandrunsontheclientmachine.

CertificationTraining
OnlineonVideos:
MicrosoftMCSETraining,
A+Certification,MCITP,
&Freedemos.MCSE
certificationtraining
includessimulatorsand
labs.

MoreTraining

DifferencesbetweenJavaScriptandJava
JavaScript

Java

JavaScriptisaclientsidescriptingLanguagewhichmeansthatitisinterpretedandnot
Compiledonserverbefore
compiledtoanyparticularmachine/os,makingitplatformindependent,however,onlytoa
executionontheclient.
specific"useragent"(browser).
ObjectBased.Usesbuiltin,extensibleobjects,butnoclassesorinheritance.

ObjectOriented.Applets
consistofobjectclasses
withinheritance.

Notneccessarytodeclarevariabledatatypes.

Variabledatatypesmustbe
declared.

DynamicBinding.Objectreferencescheckedatruntime.

StaticBinding.Object
referencesmustexistat
compiletime.

Secure.Cannotwritetoharddisk.

Secure.Cannotwriteto
harddisk.

CodeembeddedinHTML.

Eventdriven=eventstriggerfunctions.e.g.,mouseclick

Relativelyeasytolearnwhichenablesquickdevelopment.

CaseSensitive.

JSandVBScriptarescriptinglanguagesthataresimilarinpurpose,however,JavaScriptisaNetscapeclientside
scriptinglanguagewhichreliesonobjectsandtheirattendantmethodsandpropertiesforalargepartofits
functionality.Ontheotherhand,VBScriptissimilartoandbasedonVisualBasic.Microsoftrelieslessontraditional
objectclassesandmoreondynamicbuiltincustomizingfunctions.
MicrosoftsimplementationofNetscapesJSiscalledJscript.
ECMAScript(EuropeanCompMfrsAssoc)EMCAin1997approvedJSasaninternationalstandardwhichintends
todiminishdifferencebetweenJSandJScript.
JavaScriptcanbeembeddedintoHTMLviaa<SCRIPT>tagwithintheheadorbody.Alternativelyyoucanplace
codedirectlyintoyourexistingHTMLtags,thismethodisknownasinlinescripting.Itisthenparsedandexecuted
ontheclientmachine.
Youcanalsocallanexternalscriptbyreferencinga.jsfilewhichmustbeinASCIItextformat.
Codesample:
<SCRIPTLANGUAGE="JavaScript"SRC="myfile.js"></SCRIPT>
HowJScodeisusedinawebpage:
Codesample:
<html>
<head>
<title>Title</title>
<scriptlanguage="JavaScript">
<!
JavaScriptcodegoeshere
//>
</script></head>
Note:the//goesbeforethe>becausetheendingcommenttagcontainsJSoperators.

http://www.mcmcse.com/ciw/javascript_guide.shtml

1/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
WorkingWithVariablesandData

ObjectApackageofdata,acollectionofpropertiesandmethodsclassedunderasinglename.Aprogrammingfunction
thatmodelsthecharacteristicsofabstractorreal"objects"usingclasses.
PropertyAdescriptivecharacteristicofanobjectsuchascolor,widthorheightthattheprogrammerstipulatesinthe
creationoftheobject.Alwaysfollowedbyadotnotationafterobject.
Example:
myObject.myProperty=myValue
Method()Objectsaction.Musthaveparenthesis()attheendofthemethod.Anymethodthatreturnsavaluecanalso
becalledafunction.
Example:
document.write()
ValueThespecificcolor,widthorheightthatbelongstothepropertyofanobject.
StatementAsinglelineofcodetobeexecutedinascriptorprogram.Semicolons()areusedinJStoseperate
statementsunlessstatementsarecombined,althoughitisstillconsideredgoodcodingpracticetoincludethem.
Semicolonsarerequiredwhenusingmultiplestatementsin1lineofcode.
ConcatenationThesynthesisofcodetosimplifyitandreduceduplicationcombiningtextstrings/filesespeciallyin
conjunctionwithprompt()andalert()asshownintheexamplebelow:
Example:
Alert(Hello,+prompt(Whatisyourname?,)+.)
Note:promptalwayscomesbeforealert
VariablesThesearesymbolsornamesthatstandforavalueinyourprogram.Theyarenamedmemoryspacesthat
containvalueswhichyoucanaccessrepeatedlyandmaychangeitsownvalueaswellasthevaluesofothervariables
overthecourseofscriptsequence.Intheexpressionx+y,xandyarevariables.Variablescanbeusedtorepresent
numbers,characters,characterstringsormemoryaddresses.Allvariablesaredeclaredusingthekeywordvar.
Example:
varMynumber.
Variablesdeclaredwithoutvalueareundefinedastheyhavenovaluealthoughtisgoodpracticetodeclarevariablesfor
theclarityofyourcode.Anotherwaytodeclareavariableistodeclareandassignitavalueatthesametimesuchas
Mynumber=10.Itisimportanttonotethatvariablenamesmusteitherstartwithaletterorandunderscore(_)and
thenamesarecasesensitive.
VariableDataTypesThereare5basicdatatypes:
NumberAnynumericvaluesuchas5or245.
StringsStringsaresetofcharactersgroupedtogetherbyquotesandarethemostcommonlyuseddatatype.
Examplesare"Hello"or"Hello555".Singlequotescanalsobeused,however,youneedtomakesurethatyouusethe
sametypeofquoteatthebeginningandendofthestring.
BooleantrueorfalsevaluesMostlyusedtoTESTconditionsinJSsuchaswithacheckbox.
AJavaScriptelementsuchasafunctionorobject.
NullAspecialkeywordforthenullvalue.MostlyusedtodeterminetheSTATEofvar.

Literals:Thesearetheactual(fixed)datavaluesassignedtovariablesinthescript.Thereareseveralliteraltypes:
IntegerThesearenumbersthatarebasedononeofthefollowing3formats:
Decimal(base10)19followedbyanysetofthesesamedigits.
Octal(base8)0followedbyanysetofthedigits07.
Hexadecimal(base16)0xor0Xfollowedbyanycombinationof09,aforAF.
FloatingpointThesenumberscanbespecifiedineitherdecimalformatorengineeringEnotation.This
encompassesnumbersthatcontainadecimalpointoranexponent.
Stringliteral:anytext
KeywordsarethepredefinedidentifiersthatformthefoundationofJavaScript.Theyachievespecificresultsandperform
uniquedutiessuchasdeclaringvariableanddefiningfunctions.Keywordsandreservedwordsareforexplicitusebythe
languageandcannotbeusedasvariables,functions,objectsormethodsnames.
Expressionsarepartofastatementthatisevaluatedasavalueandrelyonvariousoperators.Youcanuseany
combinationofvariables,literals,operatorsandotherexpressionswiththeexceptionofassignmentexpressions,which
assignavaluetoavariable.Forexample,a=1awouldbetakenasavariableandthevalueassignedtoitwouldbe1.
Operatorsprovidevariouswaysofcombiningvalues(literalsandvariables)intoexpressions.Unaryoperatorsonlyrequire
asingleoperandwhilebinaryoperatorsrequire2.Thereare4basicoperatortypesoutlinedbelow.
AssignmentOperatorsThebasicassignmentoperatorisequal(=),whichassignsthevalueofitsrightoperandto
itsleftoperand.Aggregateoperatorscanbecreatedbyaddinganotheroperatorbeforethe=signtocreate
shorthandforotheroperations.Thetablebelowshowsexamplesoftheseoperations.
Shorthandoperator Meaning
x+=y

x=x+y

x=y

x=xy

x*=y

x=x*y

http://www.mcmcse.com/ciw/javascript_guide.shtml

2/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
x/=y

x=x/y

Arithmetic(aka.Computational)OperatorsArithmeticoperatorstakenumericalvalues(eitherliteralsorvariables)
astheiroperandsandreturnasinglenumericalvalue.Thestandardarithmeticoperatorsareaddition(+),
subtraction(),multiplication(*),division(/)andremainder(%).Theseoperatorsworkastheydoinother
programminglanguages,aswellasinstandardalgebra.Sinceprogrammersfrequentlyneedtoaddorsubtract1
fromavariable,JavaScripthasshortcutsfordoingthis.myVar++addsonetothevalueofmyVar,whilemyVar
subtractsonefrommyVar.
Examples:
Letx=3.x++turnsxinto4,whilexmakesxequalto2.
ComparisonOperatorsAcomparisonoperatorcomparesitsoperandsandreturnsalogicalvaluebasedonwhether
thecomparisonistrueornot.Theoperandscanbenumericalorstringvalues.Theyaredescribedinthefollowing
table:
Operator

Description

Example

Equal(==)

Evaluatestotrueiftheoperandsareequal

x==yevaluatestotrueifxequalsy.

Notequal(!=)

Evaluatestotrueiftheoperandsarenotequal.

x!=yevaluatestotrueifxisnotequal
toy

Greaterthan(>)

Evaluatestotrueifleftoperandisgreaterthan
rightoperand

x>yevaluatestotrueifxisgreater
thany

Greaterthanor
equal(>=)

Evaluatestotrueifleftoperandisgreaterthanor
equaltorightoperand

x>=yevaluatestotrueifxisgreater
thanorequaltoy

Lessthan(<)

Evaluatestotrueifleftoperandislessthanright
operand.

x<yevaluatestotrueifxislessthan
y.

Lessthanorequal Evaluatestotrueifleftoperandislessthanor
(<=)
equaltorightoperand.

x<=yevaluatestotrueifxislessthan
orequaltoy.

Examples:
3==3wouldreturnTRUEbecausethreeisequaltothree.3!=3wouldreturnFALSEbecausethestatement
'threeisnotequaltothree.'isfalse.3<=3wouldreturnTRUEbecausethreeislessthanorequaltothree.
LogicalOperators
LogicaloperatorstakeBooleanvaluesasoperandsandreturnaBooleanvalueoftrueorfalse.Theseoperatorsare
showninthefollowingtable:
Operator Description
and(&&)

Trueonlyifbothlogicalexpressionstrueotherwiseitisfalse.

or(||)

Trueifeither(orboth)logicalexpressionistrue.Falsewhenbothexpressionsarefalse.

not(!)

Returnstheoppositevalue.Falseifexpressionistrue.Trueifexpressionisfalse.

Thedifferentoperatorsareusedinconjuctionwitheachotherasshownintheexamplesbelow.
Examples:
Ifx=6andy=9,((x+y+2)==17)&&(((x+y)/3)==3)returnsFALSE.
Thebestwaytoevaluatethisistocomputetheleftandrightsidesseparatelyandthencomparethemusingtheoperator
inthemiddle.Ontheleftwehave((6+9+2)==17).Since6+9+2areequalto17thissideisTRUE.Ontherightside
wewouldhave(((6+9)/3)==3)whichgives((15/3)==3.Since5isnotequalto3,thissideisFALSE.Essentially
whatweareleftwithis:TRUE&&FALSE.&&willonlyreturnTRUEifbothexpressionsareTRUE.Inthisexampleonly1
expressionisTRUEsooverallwegetaFALSE.Belowareacouplemoreexamplesthatyoucanworkthrough.
Ifx=4andy=7,!((x/2+y)==9)||((x*(y/2))==2)returnsFALSE.
Ifx=4andy=7,((yx+9)==12)||((x*y)==2)returnsTRUE.
Note:Parentheticexpressionstakesprecedenceoverotherexpressions.Intheexample,(4+6)*2,theexpressionin
parenthesesiscalculatedfirstandthenmultiplied.

Functions,Methods,andEvents
Functionsgrouptogetherachunkofcodeunderanamedsubroutine,allowingyoutocallthefunctionwheneverits
actionisrequired.Functionsareimportantorganizationaltoolsthatallowyoutoperformthesameoperationbycalling
theparticularfunctioninsteadoflistingthefunction'scodeeverywherethatyouwanttouseit.Secondly,functionsare
usedtolinkuseractionsonawebpagewithJavaScriptcode.Itisimportanttorememberthefollowingaboutfunctions:
functionandmethodareinterchangeable.Tip:functionreturnsvalueswhilemethod()doesnot.
Functionsmanipulateobjectpropertiesandperformcalculations.
Canimproveprogramefficiencyandreadabilitybyrepeatingthespecifictaskthroughouttheprogram.
Youdefineafunctionwithinthe<SCRIPT>...</SCRIPT>tags.Itisadvisabletodefineallfunctionsinthe<Head>
sothatthefunctionwillloadbeforeanyusereventscanoccurthatmightcallthefunction.
Whendefiningafunction,itisimportantthatyoupaycloseattentiontothesyntax.UnlikeHTML,JavaScriptis
casesensitive,anditisveryimportanttoremembertoencloseafunctionwithinbrackets{},separateparameters
withcommas,anduseasemicolonattheendofyourlineofcode.
Functionsaredefinedinthefollowingformat:
functionfuncName(argument1,argument2,etc)
{statements}
CodeSample:
functionappear(){
document.d1.visibility='show'
}

http://www.mcmcse.com/ciw/javascript_guide.shtml

3/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
Noticetheparenthesesafterthefunctionname.Itisveryimportantthatyouincludetheseparentheses,eveniftheyare
empty.Ifyouwanttopassaparameterintothefunction,youwouldincludethatparameterinsideoftheparentheses,
otherwisetheyareleftempty.
FunctionsarecalledusingaCallingStatementwhichisastatementthattransfersprogramexecutiontoasubroutine,
procedureorafunction.Whenthefunctioniscomplete,executiontransfersbacktothecallstatement.Ifyouspecify
arguments,theargumentswillbecomethevariableswithinthefunctionbody.PassingArgumentscanbeusedtopass
values/expressionsofdataorcodeontoafunction.Oncethevaluesareused,theyarediscarded.
CallingaFunctionAfunctionsstatementisexecuted/processedwhenitiscalledbyanotherfunctionorauserevent
(e.g.,onclick)oraseparate<script>block.
BuiltinfunctionsParse()functionseliminatethe+beinginterpretedasconcatenationwhenyouwantitasmath
operator.
parseInt():converts#toitsintegerequivalent
parseFloat():floatingpointdecimalequivalent

CodeSample
functionaddItems(){
varx=prompt("Howmanyashtrays?")
vary=prompt("Howmanytables?")
varz=prompt("Howmanychairs")
items=parseInt(x)+parseInt(y)+parseInt(z)//i/ox+y+z
alert("Youordered"+items+"items.")}
Thisfunctioncouldthenbecalledasfollows:
CodeSample
<form><inputtype="button"value="order"
onClick="addItems()"></form>
Example:
Toseewhatthiscodeproduces,clickthebuttonbelow:

order

Note:Globalvariablescanbyaccessedfromanywhereinthepage'scodeandyoumaydeclarevariablesbyassigninga
valuewiththevarstatement.Allvariablesdeclaredoutsideofafunctionareglobalandvariablesdeclaredinsideafunction
byassigningavalueareglobal.Globalvariablespersistuntilthepageisunloaded.Localvariablesareonlyvisibleinsidethe
functionthatdeclaredthem,anddisappearwhenthefunctionterminates.Youmustusethevarstatementtodeclarea
localvariable.
EventBasedModel
Aneventisanactionoroccurrencedetectedbyaprogram.Itcanbeuseractions,suchasclickingamousebuttonor
pressingakey,orsystemoccurrences,suchasrunningoutofmemory.Usersgeneratedeventsincludeloadingand
unloadingpages,mouseclicks,keystrokeswhilenavigatingthroughapageorsubmittingform.MostmodernGUI
applicationsinWindowsenvironmentsareconsideredeventdriven,astheyaredesignedtorespondtoevents.
EventHandlers
Javascriptcanalsoexecuteonevents,whensomethinghappenstothebrowser.AllexecutionsmadebyJavascriptdonot
havetobemadeinacertainsequence.Eventhandlersareusedtotellthebrowserwhattodowhenaparticularevent
occurs.PredeterminedeventhandlersincludeonClick,onMouseOver,onBlur,onmouseout,etc.
Example:
<ahref="#"onMouseOver="alert('Thisisalink.')">Thisisalink</a>
onMouseOverintheabovecodeistheeventhandler.Thiscodewouldproducethefollowing:Thisisalink.Youwill
noticethatwhenyoumoveyourmouseoverthelinkyougetanalert.
AnHTMLelementcanhavemultipleeventhandlersanycombinationofavailableeventhandlerscanbeincludedina
singletag,witheachwaitingforitsownspecificeventtotakeactionon.
EventscorrespondingtousersinteractionaredifferentfromWindowEvent,infact,eventhandlersareavailableformany
HTMLelements,fromlinkstothebrowserwindowitself.HandlersassociatedwitheachHTMLtagmaydifferdependingon
theHTMLtagbeingused.Windowrelatedeventhandlersareprocessedasattributesofthe<body>tagratherthanthe
<AHREF>tag:<bodyonLoad="window.alert('Thisisanalert.')">.Thetablebelowlistssomeofthemostcommon
eventsanddescriptions.
Event

Description

Load

HTMLdocumentloadsintobrowserwindow

Unload

HTMLdocumentinbrowserwindowisreplacedbyanotherdocumentwhenauserexitsthepage.

Focus

Thefocusedwindowisthewindowbeingviewed.Ifanotherwindowisselected,thefocusisshiftedtothat
windowandtheoriginalwindowsubsequentlylosesthefocus.

Blur

Window'sfocusismovedtoanotherHTMLdocument

Click

Userclicksonaspecifiedobject.

Change

Userchangesthevalueofaformfield

Mouseover Usermovesthemouseovertopofaspecifiedlink.

ControllingProgramFlow
JavaScriptgivesyouaccesstoconditionallooping(suchasforandwhileloops),decisionmakingstatement(suchasifand

http://www.mcmcse.com/ciw/javascript_guide.shtml

4/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
switchstatements)andobjects(suchasarrays).Aloopisaseriesofinstructionsthatisrepeateduntilacertaincondition
ismet.Eachpassthroughtheloopiscalledaniteration.Conditionsmayexistwhenascriptwillberequiredtorun
differentcommandsdependingondifferentoutcomes.Conditionalstatementsdirectprogramflowinspecifieddirections.
TherearestatementsbuiltintoJStohelpdealwithdifferentconditionswhichareexplainedbelow:
IfStatementThisconditionisusedtoconditionallyexecuteasingleblockofcode.Theifstatementcanbeusedin
conjunctionwiththeelsestatementdescribednext.
ElsestatementUsedtoevaluatemultipleconditionswhereanyofanarraycouldbetrue.Whencombinedwithan
IFstatement,asecondblockofcodewillexecuteifthefirststatementisfalse.
CodeSample:
VaruserAnswer=""
userAnswer=prompt("Guessanumber.","")
if(userAnswer==25){
alert("Youwin")
}else{
alert("Tryagain")
}
If(i++==10):varIwouldbeincreasedinvalueby1thenexttimeitisaccessed.
If(++i==10):varIwouldincreaseinvalueby1beforebeingcomparedto10.
SwitchStatementMatchesanexpressionwithaspecifiedcaseandexecutesthecorrespondingstatements.The
switchstatementactsasmultipleIfstatements(comparesavalueagainstanothervalue).However,itallowsyou
tospecifyadefaultsetofstatementstoexecuteifthescriptdoesnotfindamatch.(IntroducedinJS1.2
specificationwhichrequiresabrowsersversion4orhighertofunction.)
Example:
switch(expression/variable1){
caselabel0:
//dothis,oneormorestatements
break
caselabel1:
//dothis,oneormorestatements
break
caselabel2:
//dosomethingelse,oneormorestatements
break
default:statement}
WhileStatementStatement(s)LOOPSaslongasacertainconditionremainstrue.Iffalse,itmaynotexecutethe
statementsevenonceandthescriptskipstothenextline.Misusebynotterminatingthewhileloopcanfrustrate
users.
Example:
varnum=0
while(num<10)or(A==B){
document.write(num)or(AisequaltoB)
num++
}
DoWhileStatement:Exactlylikethewhilestatementexceptitdoesnotchecktheconditionalexpressionuntilit
executestheloopthe1sttimewhichguaranteesthatthecodeisexecutedatleastonce.(IntroducedinJS1.2
specificationwhichrequiresaversion4orhigherbrowsertofunction.)
Example:
do{
//dothis,oneormorestatements
}while(conditione.g.A==B)
ForStatementUsedtocyclethrougheachpropertyofanobjectoranarrayelement.Theprimarypurposeisto
repeatagroupofstatementsforsomeparticularrangeofvaluesuntilatestconditionisfalse.Theloopuses
mathematicalformulas,usuallyacounter,toincrement/decrementavariableuntiltheconditionisnottrue.
Example:
varx=0
for(i=0i<5i++){
x+=i
}
alert("x="+x)
TheBreakStatementExits/stopsaloop.Ifacertainconditionismettheuserisallowedtobreakoutsideofloop
andgoontothenextstatement.TypicallyusedinsideofIFstatementaswellasw/intheFOR,SWITCH&WHILE
statements.Inthefollowingexample,theisNaN()methoddetermineswhetheravalueisanumericdatatype.The
loopwillcontinueuntilauserentersavalueotherthana#.
Example:
if(isNaN(numericalData))break
TheContinuestatementAbortsonlythissingleiterationoftheloop.Usedonlywithinfor/whileloopstoforce
controlbacktothetopoftheloopi.e,skip/bypasscommand.Whenexecutionreachesacontinuestatement,all
statementsb/wit&endoftheloopblockareskippedandexecutionreturnstothetop/beginningoftheloopagain.
Inthefollowingexamplenotethat:Result=x=10.Xincrementsby1untilitreaches5,therefore,1+2+3+
4=10
Example:
A=1,B=6,C=3.
while(conditionA<B){
//dothis,oneormorestatements.e.g.A++

http://www.mcmcse.com/ciw/javascript_guide.shtml

5/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
if(conditionA>C){continue}
//dosomethingelse,oneormorestatements
}

TheJavaScriptObjectModel

JSwasdesignedexplicitlyforwebpageuse.Itdividesobjectsinto3groups:browserobjects,languageobjects(akaBuilt
inobjects)andHTMLobjects.Objectshavemethodsandpropertiesthatcanbeaccessedusingdotnotationsuchas
window.status.Thevariousobjecttypeswillbediscussedinmoredetailbelow:
BrowserObjectsSpecialbrowserobjectshavebeenbuiltintotheJSlanguagetotakeadvantageofthedifferent
featuresandcapabilitiesprovidedbythebrowser.Theprimarybrowserobjectsarelistedbelow:
WindowObject:ThewindowsobjectisthetopsubjectanddefaultintheJSobjecthierarchy.Therefore,thereis
NOneedtoreferencebyitsname.Everybrowserwindowthatiscurrentlyopenhasacorrespondingwindowobject
andallotherobjectsarechildrenofoneofthewindowobjects.Whenopeninganadditionalwindow,itcan
referencedbythewindowname.Therearespecialwindowobjectsshownbelow.
Target Description
parent

Awindoworframewhoseframesetcontainsthecurrentframe.

Self

Thecurrentwindow.

Top

Thetopmostbrowserwindow.

Blank

Loadsthedocumentintoanewunnamedwindow.

CommonWindowMethods
Alert()

Displaysadialogueboxtocommunicatewithusers.

Prompt()

Requestsuserinputinatextfieldviadialogbox.

Confirm() Allowsuserstoconfirmtheirresponseinthealertwindowdialogbox.
Open()

Createsanewcontrolwindow.

Close()

Closesthecontrolwindow.

Let'slookacoupleofexamplesthatutilizewindowobjects.Thefirstistheverycommonpopupwindow.Inour
example,thewindowwouldopenwhenalinkisclicked.
CodeSample:
<ahref="#"
onClick="MyWindow=window.open('http://www.myfavoritesite.com','MyWindow','toolbar=no,
location=no,resizable=no,width=200,height=400')returnfalse">clickhere</a>
Thenextexamplewillshowhowwindowsobjectscanbeusedwithawithstatementtorelateseveral
properties/methodstoasingleobjectwhichamoreefficientapproach.(NotsupportedinIE3.0).
CodeSamples:
Usingwithstatement
myWindow=open("","newwin","height=100,width=100")
with(myWindow.document){
open()
bgColor="blue"
fgColor="white"
write("HelloSara")}
Withoutwithstatement
MyWindow.document.open()
MyWindow.document.bgColor=blue
MyWindow.document.fgColor=white
MyWindow.document.write=(HelloSara)
MyWindow.document.close()10
DocumentObject:Thedocumentobjectcontainspropertiesforeverylink,anchorandformonapageandalso
subelementsofthoseelements.Italsocontainspropertiesforbackgroundcolor,title,foregroundcolor,linkcolors
andotherpageattributes.Itisdefinedwhenthe<body>tagisevaluatedinanHTMLpage.Theobjectexistsas
longasthepgisloaded.Thedocumentobjecthasthefollowingmethods:
Method

Description

clear()

Completelyerasesadocumentwindow

close()

Displaystheresultsofwriteoperationsonthepage.

open()

Usedwithwriteoperationstostartbufferedoutput.

write(str)

Usedtowriteanystringexpressiontothecurrentdocument

writeln(str) Sameaswriteexceptitaddsacarriagereturnafterwritingarguments.
Anexampleofthedocumentobjectinactionwouldbeapagelastmodifiedscriptwhichwillreturnthedateand
timedocumentwasmostrecentlysaved/modified.
CodeSample:
document.write(Thispglastupdated+document.lastModified)
HistoryObject:Allowsyoutoaccessbrowserhistorythroughscripts.Thisislikeusingthebrowsersbackand
forwardbuttons.ThehistoryobjecthasalengthpropertywhichindicateshowmanyURLsarestoredinthehistory

http://www.mcmcse.com/ciw/javascript_guide.shtml

6/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
list.Thehistoryobjectusesback(),forward()andgo()methods.Anexamplewouldbehistory.back().
LocationObject:DescribestheURLofadocumentandhaspropertiesthatrepresenttheprotocol,hostname,
pathandport.Cancreatebuttons,hypertext,graphic,etc.linkstosenduserstodifferenttargets.Thetablebelow
liststhelocationobjects:
Property

Description

href

Mostfrequentlyusedproperty.SpecifiestheURLofafileorsite

Protocol

httporftpcurrentlyinuse

Host

Referstothe

Hostname SpecifiesthehostnameoftheURL
Port

Specifiesport#(if1isprovided)

Pathname Indicatesthepathtothedesiredfile
Search

Returnsthetextfollowingthe?character(ifasearchstringispresent)

Hash

Specifiestheinternallinkofanchornamefollowedby(#)intheURL.

CodeSample:
location.href=http://www.ciwcertified.com
<form><input=buttonvalue=onClick=location.href=http://www.ciwcertified.com></form>
ImageObject:mostpopularuseisformouseoveranimatedbuttonsinIE4.0andNetscape3.0+.Theimage
objectloadsasanarrayandhasnobuiltinmethods.Thereplacednewimagemustbelessthanorequalinsizeto
theoriginal.
Examples:
document.images[0].src=newImage.jpg
document.[imageName].src="newImage.gif"
Tocreateaninstanceoftheimageobject:
imageVarName=newImage()
Toassignasource:
imageVarName.src="image.gif"
Properties

EventHandlers

Src

OnAbort:occurswhenusercancelsloadingimage

HeightandWidth

OnError:activatesifimghasbecomecorrupted/failstoload

Length

OnKeyDown

Lowsrc:loadslowbandwidthimgs OnKeyPress
Complete

OnKeyup

Hspaceandvspace

OnLoad:activateswhenimgfinishedloadingintothebrowser.

Border

Reflectstheborderattribute

LanguageObjects
JSutilizesHTML<forms>anditselementsasobjectsthatcanbeusedtomanipulateDate,Array,MathandString
informationinusefulways.Theseobjectsarealsoknownasbuiltinobjectsandarenotpartofthecontainment
hierarchy.
StringObject:Informationabouteachspecificstringisstoredinproperties.Canbeasetoftext,#,or
combinationofcharactersthatactsastext,suchasliterals(Howareyou?)orvariables(userName).Has
methodsthatallowyoutowritestringsofcharactersaswellastestforthepresenceofcertaincharacters.Form
ValidationusingStringMethods:(Importantforclientside)cantestforcertainpatternsincreditcard#saseachcc
havetheirspecificstarting#s.ValidateEmailaddressbycheckingwhetherornotithas@.
1.extractasubset(calledasubstring)foragivenstring
2.retrievethenumberofcharactersfromastring:length()
3.findthepositionofgivencharactersinastring:indexOf()
Thestandardwaytocreateastringis:varstr=newString("Hello")butcanbetypedlooselyalso:hello.bold()
Commonlyusedstringmethodsinclude:
Method

Description

toLowerCase()

Convertsallcharactersinstringtolowercase

toUpperCase()

Convertsallcharactersinstringtoupppercase

indexOf(string)

Searchesforwardthroughastringforthegivenstringvalue

lastIndexOf(string) Searchesbackwardthroughastringforthegivenstringvalue
Substring(A,B)

Returnsasectionofastring,definedbyabeginning(A)andending(B)indexnumber

charAt(#)

Returnsasinglecharacterfromastringattheindex#specified

Examples:
Hello,World!.length
Willreturntheintegervalueof13.

http://www.mcmcse.com/ciw/javascript_guide.shtml

7/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
sarachoe@ABC.com.indexOf(choe@,0)
Wouldreturnavalueof4.
sarachoe@ABC.com.indexOf(choe@,5)
Wouldreturnavalueof1.
Abc1234xyz.substring(3,7)
Wouldreturnthevalue1234
ABCDE.charAt(3)
ResultisD
StringObjectFormattingMethods:document.write(insertthemethodslistedbelow)
Method

Example

HTMLEquivalent

Anchor("anchorname") "part2".anchor("p2")

<aname="p2">part2</a>

big()

"Welcome".big()

<big>Welcome</big>

Blink()

"New".blink()

<blink>New</blink>

Bold()

"Hot".bold()

<b>Hot</b>

Fixed()

"NamePhone".fixed()

<TT>NamePhone</TT>

fontcolor("color")

"savage".fontcolor("blue")

<TT>NamePhone</TT>

fontcolor("color")

"savage".fontcolor("blue")

<fontcolor="blue">savage</font>

Fontsize(size)

"Dude".fontsize(6)

<fontsize="6">Dude</font>

italics()

"Other".italics()

<I>Other</I>

link("url")

"NASA".link("http://nasa.gov") <ahref=http://nasa.gov>NASA</a>

Small()

Dontlook.small()

<small>Dontlook</small>

Strike()

Dontlook.strike()

<strike>Dontlook</strike>

sub()

H+2.sub()+0

H<sub>2</sub>0

sup()

E=MC+2.sup()

E=MC<sup>2</sup>

ToLowerCase()

Hello.toLowerCase()

hello

ToUpperCase()

Hello.toUpperCase()

HELLO

StringObjectSpecialCharacters
Character Description
\b

Backspace

\f

FormFeed

\n

NewLine

\r

CarriageReturn

\t

Tab

\"

DoubleQuote

\'

SingleQuote

\\

Backslash

ArrayObject
Thearrayobjectisusedtogrouprelateddatatobeassociatedwithasinglevariable.Anarrayisaseriesofobjects
allofwhicharethesamesizeandtype.Eachobjectinanarrayiscalledanarrayelement.Forexample,youcan
haveanarrayofintegersoranarrayofcharactersoranarrayofanythingthathasadefineddatatype.Each
elementinthearrayhasthesamedatatypeandcanhavethesameordifferentvalues,andtheentirearrayis
storedcontiguouslyinmemorywithnogapsinbetween.Anemptyarrayiscreatedusingthesyntax:Myarray=
newArray().Newisakeywordusedtoinitializethearray,similartothevarkeywordinvariable.Oncethearrayis
declared,youassignmultiplevaluestotheelementsofthearrayasshownintheexamplebelow:
Examples:
varquestions=newArray(10)//therewillbeatotalof11elements
question[0]=Whatis?
question[1]=Whatis?
alert(questions.length)://willreturn11
Todeclareandassignavalueatthesametime,trythefollowing:
mybook=newArray("book1","book2","book3")
Someobjectshavebuiltinarrays:e.g.,windowobjectshasabuiltinframesarraythatallowsyoutoreference
framesbytheirindex#withinthatarray.
DateObject
Thedateobjectisusedtodealwiththeconversionbackandforthbetweenourcalendardatingsystemandthe
computersdatesystem.Thedateobjectonehas1property(prototype)whichallowsyoutoaddadditional
properties.
Adateinstancecanbecreatedinoneofthefollowingways:
newDate()

http://www.mcmcse.com/ciw/javascript_guide.shtml

8/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
newDate(datestring)
newDate(yr,mon,day)
DateobjectsbuiltinMethods
Method

Description

getDate()

Retrievesthedaynumber(131)

GetDay()

Retrievesthedayofweekvalue(060isSunday)

getMonth()

Retrievesthemonthnumber(0110isJanuary)

getYear()

Retrievesthenumberofyearssince1900

getHours()

Retrievesthehournumber(0230ismidnight)

getMinutes()

Retrievesthenumberofminutes(059)

getSeconds()

Retrievesthenumberofseconds(059)

getTime()

RetrievesthenumberofmillisecondsthathaveelapsedsincemidnightonJan1,1970

setDate(value)

Assignsthedatewithinthemonth(131)

ToLocaleString() Returnsthedateinthelocalsystem'sformat
TheMathObject:
Themathobjectisusedforvariousformsofmathematicalcalculationandisusefulforworkinginscientificfieldsof
study.Themathobjectisastaticobjectthatcontainssomeconstantvalues(e.g.PI)asproperties.Youdonot
needtocreateanewinstanceandcannotreassignvaluesaswithDateobject.
Examples:
varnum=5.2
alert(num)
varnewnum=Math.round(num)
alert(newnum)

InteractiveForms

1.retrievesusersinputteddata
2.launchesscript(eventhandlers)
3.cancreatedropdownboxofURLchoices
4.cancreatecheckboxtocontroltheappearanceofnextpg
Thereare2waysofreferringtoFormObjects:
1.1.Byname:
<formname="myForm">
<inputtype="text"name="firstName">
</form>
document.myForm.firstName.value
2.Byindexnumberintheformelementsarray:
document.forms[0].elements[0].
Featuresofformobjects:
PropertiesDescription
Action
specifiestheURLforthedatasubmission
Elements arrayofobjects
Encoding StringcontainingtheMIMEencodingoftheform(specifiedintheENCTYPEattribute)
Length
#ofelementsintheform
Method
submissionmethodofdatatoaserver
Name
asdefinedinthe<form>tag
Target
nameofthewindowtowheresubmissionsaredirected
FormsutilizeseveralHTMLobjectsthatarelistedbelow.
ButtonObject
ThisisthesimplestofallobjectsandcanbeusedtoactivateafunctionoropenaURL(amongotherthings).
PropertiesMethodsEventHandlers
Name
Click()
onClick
Value

Example:
<inputtype="button"value="doaction"onClick="function()">
document.formName.buttonName.value="NewValue"
document.formName.buttonName.value
CheckboxObject
ThecheckboxobjectcreatesaboxthatreturnsaBooleanvalueoftrueorfalsedependingonwhetherornotitis
checked.
Properties
MethodsEventHandlers
checked
Click()
onClick
DefaultChecked

Name

Value

TextandTextareaobjects
ThetextobjectcreatesatextboxthatcanonlydisplayasinglelineoftextwhereasTextareaobjectscandisplay
multiple,scrollinglinesoftext.
Properties MethodsEventHandlers

http://www.mcmcse.com/ciw/javascript_guide.shtml

9/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
defaultValueBlur()
onBlur:processeswhenthecursorismovedawayfromthisobject
Value
focus() onFocus:processeswhencursorismovedtothisobject
Name
select() onSelect:processeswhentextinthisobjectishighlighted
Example:
Name:<BR>
<INPUTTYPE="text"SIZE="30"NAME="name"value="Yournamehere"><BR>
Thiswouldcreate:
Name:

Yournamehere

Example:
<textareacols='25'rows='5'name='name'></textarea>
Thiswouldcreate:

RadioButtonObject
Usedtoselectamongmutuallyexclusiveoptionsyes/no.Notboth.
Properties
MethodsEventHandlers
DefaultCheckedClick()
onClick
checked

Value

Name

Length

TheSelectObject
AdropdownlistoralistboxofitemsusedinanHTMLform.CommoneventhandlersareonChange,onBlurand
onFocus.
FORMValidation
Usedtoverifycorrect/validformsubmissions,increaseendusersatisfactionandconservebandwidth.Notentirelypossible
tovalidateallformsubmissions,butsomevalidationisbetterthannone.Youshouldnotethatsomeusersmayget
frustratedbyinterveningvalidation.
FormValidationEventHandlers
FormvalidationwithJavascriptisefficientasvalidationtakesplaceontheclientmachine(sothereisnodelayinorderto
contactaremoteserver).Formvalidationisaccomplishedbyintegratingformeventhandlersandotherprogramflow
structures,suchasifelsestatements,forloop...etc.
Eventhandlersforforms
Onblur

ExecutesJavaScriptwheneverauser,usingthemouse,movesthefocusawayfromaformelement.Youuse
ittocheckeachelementindividuallyandasktheusertofixtheinvalidinputbeforemovingon.

Onsubmit

ExecutesJavaScriptwheneversomeoneclicksthe"submit"button.Novalidationtakesplaceuntiltheuser
submitstheform.

Example:
Samplecodefragmentforpasswordfieldvalidation:
<scriptLanguage="JavaScript">
<!
functionForm1_Valid(theForm){//checktoseeifthefieldisblank
if(theForm.Alias.value=="")}
{
alert("Youmustenteranalias.")
theForm.Alias.focus()
return(false)
}//requireatleast5charactersbeentered
if(theForm.Alias.value.length<5)
{
alert("Pleaseenteraminimumof5charactersinthe\"Alias\"field.")
theForm.Alias.focus()
return(false)}//checkifbothpasswordfieldsareidentical
{
alert("Thetwopasswordsaredifferent.")
theForm.Password2.focus()
return(false)}//></script>
YouwillneedtospecifytheformactionastheJavaScript:
<formaction="javascript.asp"method="POST"onsubmit="returnForm1_Valid(this)"name="Form1">

CookiesandJavaScriptSecurity
CookiesweredevelopedbyNetscapeandaretextfilesstoredontheuser'scomputerandsenttotheusersbrowserwhen
ausergeneratesanHTTPrequest.Referredtoas"persistentclientstateHTTPcookies"and"persistentHTML".Help
maintainstate,aidauthentication,removeredundantstepsandtrackuserbehavior.Thereare2actionscanoccur:
1.Smallmemoryresidentpiecesofinformation,areoriginallystoredinthesystemmemoryorfilesofyourcomputer.A
servercandepositcookiesontheuser'sharddrive
2.Anycookiesalreadyontheuser'ssystemthatmatchtheserver'sdomaincanbepassedalongintherequestheader.
Mostbrowsershaveoptionsthatallowtheusertodeterminehowtheywishtodealwithcookies.NetscapeNavigator4.0
hasthefollowingoptions:

http://www.mcmcse.com/ciw/javascript_guide.shtml

10/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
1.Acceptallcookies
2.Acceptonlycookiesthatgetsentbacktotheoriginatingserver.Disablessharedcookies.
3.Disablecookies
4.Warnbeforeacceptingacookie
WhocanSendCookies?
Crossdomainpostingisimpossible(i.e.,1domaincannotdepositacookieforanother).Somedomains"share"cookies
becausesomesites(Amazon,Yahoo,DoubleClick)belongtothesamenetworkassubdomains(whichallowsanother
networkmembertoloadcontentontoitsanothermembersmainsearchpage).Forexample,wheneverauseraccesses
Yahoosmainpage,theuserisalsoaccessingAmazon.EventhoughtheusermayhaveonlyvisitedYahoo,thecookiecan
besetfromanothersite.
StoringCookies
Therearerulesthatgoverntheuseofcookies.InternetExplorerlimitsyouto1cookieperdomain,whereasNetscape
allowsupto20pairsperdomain.Ausercanstorenomorethan300cookiesontheirharddrive.HTTPheaderforcookie
canbenolargerthan4kb.Netscapestoresinasingletextfilenamedcookies.text.ProgFiles\Netscape\Users\Username
directory.IE4.0storestheminWindows\TemporaryInternetFiles\*directory.Cookieswillpersistuntiltheirexpiration
date.Theusercanalsowritetheirautoexec.batfiletodeletecookiefileseverytimethemachineboots.Theycanalso
bereassignedbyaddinganexpirationdatethathasalreadypassed.
WhyuseCookies?
Authenticationnoneedtoenterthepasswordagain.Hazardisotherusercanaccessthepagewithoutpermission.
Storinguserinformatione.g.,os/browsertype,ISP,IPaddress,historyofsitesvisited.
Statemaintenancewithcookies.Whenuserreturns,theycanresumeatthepointwheretheyleft.Forexample,it
couldbeusedtosaveyourspotinanonlinegameorallowavisitortoclickonlyoncetomakeapurchaseinanonline
store.

JavaScriptandCookies
Cookiescanbeassignedusingthefollowingmethods:
document.cookie="name=value"//thisisallthatsrequiredbut,canalsobrwrittenas:
document.cookie="name=valueexpires=datesecure"
Youcantestforcookiepresenceusingthefollowingmethod:
alert(document.cookie)
JavaScriptSecurityIssues
JScanlaunchHelperprogramswhichhackerscanmanipulate.Maliciousandaccidentalprogramscangenerateinfinite
sequencesthatmaycausethebrowsertohang.Usermustquitthebrowsertostop.

ControllingFramesinJavaScript
Frameshelptomaximizethesophisticationofyourwebsitebyallowingyoutoleavesomeinformationwiththeuserat
alltimes.Thistechniqueprovidesbotheaseofnavigation,andameanstocontroltheusers'pathsanddestinations.
UnderstandingFramesandTargets
Framesexistwithinframesetsandwillusuallyhaveadefaultsourcefile.Theexamplebelowshowsasimpleframesetthat
wouldcreate2framesonthepage,eachcovering50%ofthepage.
Example:
<HTML>
<HEAD>
<TITLE>MasterPage</TITLE>
</HEAD>
<FRAMESETCOLS="50%,50%">
<FRAMESRC="pagea.html">
<FRAMESRC="pageb.html">
</FRAMESET>
</html>
Tocreateamorecomplexarrangementofwebpagesyoucanplaceaframesetanditsassociatedframeswithinanother
frameset,whichisknownasnestingframes.Thefollowingexampleshowsonewayinwhichthiscanbedone:
Example:
<FRAMESETROWS="*,50%">
<FRAMESETCOLS="25%,25%,*">
<FRAMESRC="one.htm">
<FRAMESRC="two.htm">
<FRAMESRC="three.htm">
</FRAMESET>
<FRAMESRC="four.htm">
</FRAMESET>
BreakOutofFrames
Toensurethatusersloadyourpageinthebrowser'smainwindow,insteadofloadinginanothersite'sframe,youaddthe
followingscriptintotheHEADportionofyourdocument:
if(window!=top)top.location.href=location.href
2waystoTargetFrames
1.BytargetnamedenotedbytheframesNAMEattribute:
Parent=thefilecontainingtheframesetinwhichthecurrentlyselectedframeisdefined.Itloadsthefile
intotheimmediateparent(theframe,itself)ofthedocumentthelinkisin.
Top=highestwindowobjectinthehierarchyandtheparentofallparents.Itloadsthedocumentintothe
topmostwindow.Ifthetopmostpagedoesn'tuseaframe,theobjectmodelhasonlyonelevelofwindow
objects,whichmeansthattop=window.Casesensitive.
2.Bynumberintheframesarray:
YoumaycontrolnavigationbetweenframesusingthefollowingHTMLcodestocreatedifferentnavigationallinks:

http://www.mcmcse.com/ciw/javascript_guide.shtml

11/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
<AHREF="javascript:history.reload()">Reload(thisframe)</A>
<AHREF="javascript:history.back()">Back(thisframe)</A>
<AHREF="javascript:history.forward()">Forward(thisframe)</A>
<AHREF="javascript:parent.frames[2].history.reload()">Reload(bottomrowframe)</A>
<AHREF="javascript:parent.frames[2].history.back()">Back(bottomrowframe)</A>
<AHREF="javascript:parent.frames[2].history.forward()">Forward(bottomrowframe)</A>
Changingtwoormoreframes
<form><inputtype=buttonvalue=ChangeFrames
onClick=changeFrames()></form>
<script>functionchangeFrames(){
parent.rightTop.location.href=banner.htm
parent.rightBottom.location.href=main.htm}</script>

ClientSideJavaScript
TwopopularusesofclientsideJavaScriptaretheuseofimagemapsandbrowserdetection.
DefiningImageMaps:
Imagemapsareusedtodivideanimageintosectionsthatcanhaveindividuallinksassociatedwiththem.Inotherwords
multiplelinkscanbeassociatedwith1image.TheURLthatyouaretakentowhenclickingontheimagedependson
whichpartoftheimageyouclickon.
Example:
<mapname=myMap>
<areacoords=0,0,77,75href=home.html>
</map>
Intheaboveexample,thefirst2numbers(0and0)representtheupperleftcorner(xandycoordinates)ofthe
rectangle.Thesecondsetofnumbers(77and75)representthebottomrightcorner(xandycoordinates)ofthe
rectangle.
ScriptscanbeaddedtoImageMaps.ForexampleyoucouldaddinlinescriptswithonClick(eventhandlers)tothe<area>
tagoralert().
Example:
<mapname=myMap>
<areacoords=0,0,77,75href=home.htm
onMouseOver="status='VisitSenegal'returntrue"
onMouseOut="status=returntrue">
</map>
NavigatorObject
TheNavigatorobjectisusedtodetectausersbrowserandoperatingsystem.TheNavigatorobjectisstandalongsoit
doesnotcontainotherobjectsnorisitcontainedwithinotherobjects.
Property

Description

AppName

Browsername

AppVersion

BrowserVersion

appCodeName Browsercodename(e.g.MozillaforNetscape)
userAgent

Operatingsystem.ReturnsappCodeName/appVersion

Example:
<HTML>
<HEAD>
<TITLE>BrowserDetector</TITLE>
<SCRIPT>
<!
functionshowInfo(){
varinfo=""
info+="\nWelcome,"+navigator.appCodeName
info+="user!\nYouareusingthe"
info+=navigator.appName+"browser,\nversion"
info+=navigator.appVersion+".\nYouruseragent"
info+="informationis"+navigator.userAgent
alert(info)
}
//>
</SCRIPT>
<linkrel="STYLESHEET"type="text/css"href="jsclass.css">
</HEAD>
<BODY>
<AHREF="javascript:void(showInfo())">ClickHere</A>
</BODY>
</HTML>
Thiswouldproducethefollowing:
ClickHere

CustomJavaScriptObjects
Advantages:
1.Youcancreatesophisticatedsolutionswithaminimumofcoding
2.YoucanrepresentprogrammingconstructsasobjectsallowingUtocodeefficientschemesforevaluating
forms/creatingclientsidedatabases.

http://www.mcmcse.com/ciw/javascript_guide.shtml

12/13

9/28/2016

CIWJavaScriptStudyNotesandTutorial
CreatingaCustomJavaScriptObject:
Theobjectissimilartoadatabaserecordinthatitcontainsvariousfieldsorpropertiesthataresharedamonginstancesof
thatobject.AConstructorisaspecialfunctionthatenablesyoutodefineorcreateinstancesandacustomJavaScript
object.Itisthebuildingblockofallcustomobjects.Itdefinesthepropertiesandmethodsofyourobject.Defininga
constructoristhe1ststepincreatinganobject.Specifically,aconstructorcreatesanemptytemplatefromwhichreal
timeobjectscalledinstancescanbegenerated.
Example:
FunctionproductObject(id,item,description,material,price){
This.id=id
This.item=item
This.myDescription=description//2wordsdonthavetomatch.But
descriptionmustmatchthefunctionsargumentlistparameter.
This.material=material
This.price=price
}
Theaboveexampleisaconstructor.Id,item,description,materialandpriceareparameters.
CreatinganInstance
InstantiationOncetheconstructorisdefined,youneedtocreatenewinstancesoftheobject.Afteryouinstantiatenew
copiesoftheobject,youwillthenpopulatetheobjectpropertieswithinfo.Toinstantiateandpopulatethepropertiesof
newinstancewithactualdata,youmustdeclarevariables.
Example:
Ashtray=newproductObject(hf01,MakeAshtray,Senegalashtray,wood,$30.00)
Vardeclaredparametersaredefined.
IntheaboveexamplewedeclareourvariableAshtrayandthendefineparameterssuchasMakeAshtray,Senegal
Ashtray,etc.Itismoresensibletousearrayvariablesratherthancreatingindividualvariablesasabove.Theexample
belowshowshowthiscanbedone.
Example:
Varproduct=newArray()
Product[0]=newproductObject(hf01,maskashtray,Senegalashtray,wood,$30.00)
Product[1]=newproductObject(hf02,maskchair,ivorysculptor,mahogany,$130.00)
CreatingObjectMethods:
Toretrieve(view)theinfoyoujuststoredininstances,youshuddefineamethod(asmany,assimpleorassophisticated
asyouwantasyouwant).Ifyoudontcreatefunctionasmethod,youcannotusetheTHISkeywordandthecalling
statementwouldbedifferent.First,addthemethodThis.displayOne=displayonetotheinitialconstructor.Notethat
therearenoparenthesesafterthismethod.Iftherewere,thecodewouldcallthefunctionatthatmoment.
Example:
FunctionproductObject(id,item,description,material,price){
This.id=id
This.item=item
This.myDescription=description
This.material=material
This.price=price
This.displayOne=displayOne
}
<selectname=itemName>
for(I=0I<product.lengthI++){
document.write(<option>+product[I].item)
}
<inputtype=buttonvalue=GetinfoonClick=varI=
document.prodForm.itemName.selectedIndex
product[I].displayOne()>
functiondisplayOne(){
content=content+=<html><head><title>+this.item+</title></head>
content+=<body>
content+=<tr><TD>Description:+this.description
newWindow(oneWindow)
}
CreatingFunctionsforyourObjects
Whenyouneedtoretrieve/viewmultipleobjectsinanarray,youneedtocreateafunction,e.g.,ifelse,aswellas
window.openthatshowsallproducts.Methodsoperateonlyonasingleinstancesofobjectsratherthanallobjects.
ADVERTISE|PARTNERSHIPS|PRIVACYPOLICY|DISCLAIMER|19982015|CONTACT

ITShowcase

http://www.mcmcse.com/ciw/javascript_guide.shtml

13/13

S-ar putea să vă placă și