Wednesdayadobe

adobe flash player 10 3  时间:2021-02-20  阅读:()
LearningACTIONSCRIPT3.
0Lastupdated5/2/2011LegalnoticesLegalnoticesForlegalnotices,seehttp://help.
adobe.
com/en_US/legalnotices/index.
html.
iiiLastupdated5/2/2011ContentsChapter1:IntroductiontoActionScript3.
0AboutActionScript1AdvantagesofActionScript3.
01What'snewinActionScript3.
02Chapter2:GettingstartedwithActionScriptProgrammingfundamentals5Workingwithobjects7Commonprogramelements15Example:Animationportfoliopiece(FlashProfessional)17BuildingapplicationswithActionScript19Creatingyourownclasses23Example:Creatingabasicapplication25Chapter3:ActionScriptlanguageandsyntaxLanguageoverview33Objectsandclasses34Packagesandnamespaces34Variables44Datatypes47Syntax59Operators64Conditionals69Looping71Functions74Chapter4:Object-orientedprogramminginActionScriptIntroductiontoobject-orientedprogramming85Classes85Interfaces99Inheritance101Advancedtopics109Example:GeometricShapes1151Lastupdated5/2/2011Chapter1:IntroductiontoActionScript3.
0AboutActionScriptActionScriptistheprogramminglanguagefortheAdobeFlashPlayerandAdobeAIRrun-timeenvironments.
Itenablesinteractivity,datahandling,andmuchmoreinFlash,Flex,andAIRcontentandapplications.
ActionScriptexecutesintheActionScriptVirtualMachine(AVM),whichispartofFlashPlayerandAIR.
ActionScriptcodeistypicallytransformedintobytecodeformatbyacompiler.
(Bytecodeisatypeofprogramminglanguagethat'swrittenandunderstoodbycomputers.
)ExamplesofcompilersincludetheonebuiltintoAdobeFlashProfessionalandtheonethatisbuiltintoAdobeFlashBuilderandavailableintheAdobeFlexSDK.
ThebytecodeisembeddedinSWFfiles,whichFlashPlayerandAIRexecute.
ActionScript3.
0offersarobustprogrammingmodelthatisfamiliartodeveloperswithabasicknowledgeofobject-orientedprogramming.
SomeofthekeyfeaturesofActionScript3.
0thatimproveoverpreviousActionScriptversionsincludethefollowing:AnewActionScriptVirtualMachine,calledAVM2,thatusesanewbytecodeinstructionsetandprovidessignificantperformanceimprovementsAmoremoderncompilercodebasethatperformsdeeperoptimizationsthanpreviousversionsofthecompilerAnexpandedandimprovedapplicationprogramminginterface(API),withlow-levelcontrolofobjectsandatrueobject-orientedmodelAnXMLAPIbasedontheECMAScriptforXML(E4X)specification(ECMA-357edition2).
E4XisalanguageextensiontoECMAScriptthataddsXMLasanativedatatypeofthelanguage.
AneventmodelbasedontheDocumentObjectModel(DOM)Level3EventsSpecificationAdvantagesofActionScript3.
0ActionScript3.
0goesbeyondthescriptingcapabilitiesofpreviousversionsofActionScript.
Itisdesignedtofacilitatethecreationofhighlycomplexapplicationswithlargedatasetsandobject-oriented,reusablecodebases.
ActionScript3.
0isnotrequiredforcontentthatrunsinAdobeFlashPlayer.
However,itopensthedoortoperformanceimprovementsthatareonlyavailablewiththeAVM2(theActionScript3.
0virtualmachine).
ActionScript3.
0codecanexecuteuptotentimesfasterthanlegacyActionScriptcode.
ThepreviousversionofActionScriptVirtualMachine,AVM1,executesActionScript1.
0andActionScript2.
0code.
FlashPlayer9and10supportAVM1forbackwardcompatibility.
2LEARNINGACTIONSCRIPT3.
0IntroductiontoActionScript3.
0Lastupdated5/2/2011What'snewinActionScript3.
0ActionScript3.
0containsmanyclassesandfeaturesthataresimilartoActionScript1.
0and2.
0.
However,ActionScript3.
0isarchitecturallyandconceptuallydifferentfrompreviousversionsofActionScript.
TheenhancementsinActionScript3.
0includenewfeaturesofthecorelanguageandanimprovedAPIthatprovidesincreasedcontroloflow-levelobjects.
CorelanguagefeaturesThecorelanguagedefinesthebasicbuildingblocksoftheprogramminglanguage,suchasstatements,expressions,conditions,loops,andtypes.
ActionScript3.
0containsmanyfeaturesthatspeedupthedevelopmentprocess.
Run-timeexceptionsActionScript3.
0reportsmoreerrorconditionsthanpreviousversionsofActionScript.
Run-timeexceptionsareusedforcommonerrorconditions,improvingthedebuggingexperienceandenablingyoutodevelopapplicationsthathandleerrorsrobustly.
Run-timeerrorscanprovidestacktracesannotatedwithsourcefileandlinenumberinformation,helpingyouquicklypinpointerrors.
Run-timetypesInActionScript3.
0,typeinformationispreservedatruntime.
Thisinformationisusedtoperformrun-timetypechecking,improvingthesystem'stypesafety.
Typeinformationisalsousedtorepresentvariablesinnativemachinerepresentations,whichimprovesperformanceandreducesmemoryusage.
Bywayofcomparison,inActionScript2.
0typeannotationsareprimarilyadeveloperaidandallvaluesaredynamicallytypedatruntime.
SealedclassesActionScript3.
0includestheconceptofsealedclasses.
Asealedclasspossessesonlythefixedsetofpropertiesandmethodsthataredefinedatcompiletime;additionalpropertiesandmethodscannotbeadded.
Theinabilityofchangingaclassatruntimeenablesstrictercompile-timechecking,resultinginmorerobustprograms.
Italsoimprovesmemoryusagebynotrequiringaninternalhashtableforeachobjectinstance.
Dynamicclassesarealsopossibleusingthedynamickeyword.
AllclassesinActionScript3.
0aresealedbydefault,butcanbedeclaredtobedynamicwiththedynamickeyword.
MethodclosuresActionScript3.
0enablesamethodclosuretoautomaticallyrememberitsoriginalobjectinstance.
Thisfeatureisusefulforeventhandling.
InActionScript2.
0,methodclosuresdonotrememberwhatobjectinstancetheywereextractedfrom,leadingtounexpectedbehaviorwhenthemethodclosureiscalled.
ECMAScriptforXML(E4X)ActionScript3.
0implementsECMAScriptforXML(E4X),recentlystandardizedasECMA-357.
E4Xoffersanatural,fluentsetoflanguageconstructsformanipulatingXML.
IncontrasttotraditionalXML-parsingAPIs,XMLwithE4Xperformslikeanativedatatypeofthelanguage.
E4XstreamlinesthedevelopmentofapplicationsthatmanipulateXMLbydrasticallyreducingtheamountofcodeneeded.
ToviewtheECMAE4Xspecification,gotowww.
ecma-international.
org.
RegularexpressionsActionScript3.
0includesnativesupportforregularexpressionssothatyoucanquicklysearchforandmanipulatestrings.
ActionScript3.
0implementssupportforregularexpressionsastheyaredefinedintheECMAScript(ECMA-262)edition3languagespecification.
3LEARNINGACTIONSCRIPT3.
0IntroductiontoActionScript3.
0Lastupdated5/2/2011NamespacesNamespacesaresimilartothetraditionalaccessspecifiersusedtocontrolvisibilityofdeclarations(public,private,protected).
Theyworkascustomaccessspecifiers,whichcanhavenamesofyourchoice.
NamespacesareoutfittedwithaUniversalResourceIdentifier(URI)toavoidcollisions,andarealsousedtorepresentXMLnamespaceswhenyouworkwithE4X.
NewprimitivetypesActionScript3.
0containsthreenumerictypes:Number,int,anduint.
Numberrepresentsadouble-precision,floating-pointnumber.
Theinttypeisa32-bitsignedintegerthatletsActionScriptcodetakeadvantageofthefastintegermathcapabilitiesoftheCPU.
Theinttypeisusefulforloopcountersandvariableswhereintegersareused.
Theuinttypeisanunsigned,32-bitintegertypethatisusefulforRGBcolorvalues,bytecounts,andmore.
Incontrast,ActionScript2.
0onlyhasasinglenumerictype,Number.
APIfeaturesTheAPIsinActionScript3.
0containmanyclassesthatallowyoutocontrolobjectsatalowlevel.
Thearchitectureofthelanguageisdesignedtobemoreintuitivethanpreviousversions.
Whiletherearetoomanyclassestocoverindetail,somesignificantdifferencesareworthnoting.
DOM3eventmodelDocumentObjectModelLevel3eventmodel(DOM3)providesastandardwayofgeneratingandhandlingeventmessages.
Thiseventmodelisdesignedtoallowobjectswithinapplicationstointeractandcommunicate,maintaintheirstate,andrespondtochange.
TheActionScript3.
0eventmodelispatternedaftertheWorldWideWebConsortiumDOMLevel3EventsSpecification.
ThismodelprovidesaclearerandmoreefficientmechanismthantheeventsystemsavailableinpreviousversionsofActionScript.
Eventsanderroreventsarelocatedintheflash.
eventspackage.
TheFlashProfessionalcomponentsandFlexframeworkusethesameeventmodel,sotheeventsystemisunifiedacrosstheFlashPlatform.
DisplaylistAPITheAPIforaccessingthedisplaylist—thetreethatcontainsanyvisualelementsintheapplication—consistsofclassesforworkingwithvisualprimitives.
TheSpriteclassisalightweightbuildingblock,designedtobeabaseclassforvisualelementssuchasuserinterfacecomponents.
TheShapeclassrepresentsrawvectorshapes.
Theseclassescanbeinstantiatednaturallywiththenewoperatorandcanbedynamicallyreparentedatanytime.
Depthmanagementisautomatic.
Methodsareprovidedforspecifyingandmanagingthestackingorderofobjects.
HandlingdynamicdataandcontentActionScript3.
0containsmechanismsforloadingandhandlingassetsanddatainyourapplicationthatareintuitiveandconsistentacrosstheAPI.
TheLoaderclassprovidesasinglemechanismforloadingSWFfilesandimageassetsandprovidesawaytoaccessdetailedinformationaboutloadedcontent.
TheURLLoaderclassprovidesaseparatemechanismforloadingtextandbinarydataindata-drivenapplications.
TheSocketclassprovidesameanstoreadandwritebinarydatatoserversocketsinanyformat.
4LEARNINGACTIONSCRIPT3.
0IntroductiontoActionScript3.
0Lastupdated5/2/2011Low-leveldataaccessVariousAPIsprovidelow-levelaccesstodata.
Fordatathatisbeingdownloaded,theURLStreamclassprovidesaccesstodataasrawbinarydatawhileitisbeingdownloaded.
TheByteArrayclassletsyouoptimizereading,writing,andworkingwithbinarydata.
ThesoundAPIprovidesdetailedcontrolofsoundthroughtheSoundChannelandSoundMixerclasses.
SecurityAPIsprovideinformationaboutthesecurityprivilegesofaSWFfileorloadedcontent,enablingyoutohandlesecurityerrors.
WorkingwithtextActionScript3.
0containsaflash.
textpackageforalltext-relatedAPIs.
TheTextLineMetricsclassprovidesdetailedmetricsforalineoftextwithinatextfield;itreplacestheTextFormat.
getTextExtent()methodinActionScript2.
0.
TheTextFieldclasscontainslow-levelmethodsthatprovidespecificinformationaboutalineoftextorasinglecharacterinatextfield.
Forexample,thegetCharBoundaries()methodreturnsarectanglerepresentingtheboundingboxofacharacter.
ThegetCharIndexAtPoint()methodreturnstheindexofthecharacterataspecifiedpoint.
ThegetFirstCharInParagraph()methodreturnstheindexofthefirstcharacterinaparagraph.
Line-levelmethodsincludegetLineLength(),whichreturnsthenumberofcharactersinaspecifiedlineoftext,andgetLineText(),whichreturnsthetextofthespecifiedline.
TheFontclassprovidesameanstomanageembeddedfontsinSWFfiles.
Forevenlower-levelcontrolovertext,theclassesintheflash.
text.
enginepackagemakeuptheFlashTextEngine.
Thissetofclassesprovidelow-levelcontrolovertextandaredesignedforcreatingtextframeworksandcomponents.
5Lastupdated5/2/2011Chapter2:GettingstartedwithActionScriptProgrammingfundamentalsSinceActionScriptisaprogramminglanguage,itcanhelpyoutolearnActionScriptifyoufirstunderstandafewgeneralcomputerprogrammingconcepts.
WhatcomputerprogramsdoFirstofall,it'susefultohaveaconceptualideaofwhatacomputerprogramisandwhatitdoes.
Therearetwomainaspectstoacomputerprogram:Aprogramisaseriesofinstructionsorstepsforthecomputertocarryout.
Eachstepultimatelyinvolvesmanipulatingsomepieceofinformationordata.
Inageneralsense,acomputerprogramisjustalistofstep-by-stepinstructionsthatyougivetothecomputer,whichitperformsonebyone.
Eachindividualinstructionisknownasastatement.
InActionScript,eachstatementiswrittenwithasemicolonattheend.
Inessence,allthatagiveninstructioninaprogramdoesismanipulatesomebitofdatathat'sstoredinthecomputer'smemory.
Asimpleexampleisinstructingthecomputertoaddtwonumbersandstoretheresultinitsmemory.
Amorecomplexexampleisifthereisarectangledrawnonthescreenandyouwanttowriteaprogramtomoveitsomewhereelseonthescreen.
Thecomputerrememberscertaininformationabouttherectangle:thex,ycoordinateswhereit'slocated,howwideandtallitis,whatcoloritis,andsoon.
Eachofthosebitsofinformationisstoredsomewhereinthecomputer'smemory.
Aprogramtomovetherectangletoadifferentlocationwouldhavestepslike"changethexcoordinateto200;changetheycoordinateto150.
"Inotherwords,itwouldspecifynewvaluesforthexandycoordinates.
Behindthescenes,thecomputerdoessomethingwiththisdatatoactuallyturnthosenumbersintotheimagethatappearsonthecomputerscreen.
However,atthebasiclevelofdetailit'senoughtoknowthattheprocessof"movingarectangleonthescreen"justinvolveschangingbitsofdatainthecomputer'smemory.
VariablesandconstantsProgrammingmainlyinvolveschangingpiecesofinformationinthecomputer'smemory.
Consequently,it'simportanttohaveawaytorepresentasinglepieceofinformationinaprogram.
Avariableisanamethatrepresentsavalueinthecomputer'smemory.
Asyouwritestatementstomanipulatevalues,youwritethevariable'snameinplaceofthevalue.
Anytimethecomputerseesthevariablenameinyourprogram,itlooksinitsmemoryandusesthevalueitfindsthere.
Forexample,ifyouhavetwovariablesnamedvalue1andvalue2,eachcontaininganumber,toaddthosetwonumbersyoucouldwritethestatement:value1+value2Whenit'sactuallycarryingoutthesteps,thecomputerlookstoseethevaluesineachvariableandaddsthemtogether.
InActionScript3.
0,avariableactuallyconsistsofthreedifferentparts:Thevariable'snameThetypeofdatathatcanbestoredinthevariableTheactualvaluestoredinthecomputer'smemory6LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011You'veseenhowthecomputerusesthenameasaplaceholderforthevalue.
Thedatatypeisalsoimportant.
WhenyoucreateavariableinActionScript,youspecifythespecifictypeofdatathatitismeanttohold.
Fromthatpointon,yourprogram'sinstructionscanstoreonlythattypeofdatainthevariable.
Youcanmanipulatethevalueusingtheparticularcharacteristicsassociatedwithitsdatatype.
InActionScript,tocreateavariable(knownasdeclaringthevariable),youusethevarstatement:varvalue1:Number;Thisexampletellsthecomputertocreateavariablenamedvalue1,whichcanholdonlyNumberdata.
("Number"isaspecificdatatypedefinedinActionScript.
)Youcanalsostoreavalueinthevariablerightaway:varvalue2:Number=17;AdobeFlashProfessionalInFlashProfessional,thereisanotherwaytodeclareavariable.
Whenyouplaceamovieclipsymbol,buttonsymbol,ortextfieldontheStage,youcangiveitaninstancenameinthePropertyinspector.
Behindthescenes,FlashProfessionalcreatesavariablewiththesamenameastheinstancename.
YoucanusethatnameinyourActionScriptcodetorepresentthatStageitem.
Suppose,forexample,thatyouhaveamovieclipsymbolontheStageandyougiveittheinstancenamerocketShip.
WheneveryouusethevariablerocketShipinyourActionScriptcode,youareinfactmanipulatingthatmovieclip.
Aconstantissimilartoavariable.
Itisanamethatrepresentsavalueinthecomputer'smemorywithaspecifieddatatype.
ThedifferenceisthataconstantcanonlybeassignedavalueonetimeinthecourseofanActionScriptapplication.
Onceaconstant'svalueisassigned,itisthesamethroughouttheapplication.
Thesyntaxfordeclaringaconstantisalmostthesameasthatfordeclaringavariable.
Theonlydifferenceisthatyouusetheconstkeywordinsteadofthevarkeyword:constSALES_TAX_RATE:Number=0.
07;Aconstantisusefulfordefiningavaluethatisusedinmultipleplacesthroughoutaproject,whichdon'tchangeundernormalcircumstances.
Usingaconstantratherthanaliteralvaluemakesyourcodemorereadable.
Forexample,considertwoversionsofthesamecode.
OnemultipliesapricebySALES_TAX_RATE.
Theothermultipliesthepriceby0.
07.
TheversionthatusestheSALES_TAX_RATEconstantiseasiertounderstand.
Inaddition,supposethevaluedefinedbytheconstantdoeschange.
Ifyouuseaconstanttorepresentthatvaluethroughoutyourproject,youcanchangethevalueinoneplace(theconstantdeclaration).
Incontrast,youwouldhavetochangeitinvariousplacesifyouusedhard-codedliteralvalues.
DatatypesInActionScript,therearemanydatatypesthatyoucanuseasthedatatypeofthevariablesyoucreate.
Someofthesedatatypescanbethoughtofas"simple"or"fundamental"datatypes:String:atextualvalue,likeanameorthetextofabookchapterNumeric:ActionScript3.
0includesthreespecificdatatypesfornumericdata:Number:anynumericvalue,includingvalueswithorwithoutafractionint:aninteger(awholenumberwithoutafraction)uint:an"unsigned"integer,meaningawholenumberthatcan'tbenegativeBoolean:atrue-or-falsevalue,suchaswhetheraswitchisonorwhethertwovaluesareequal7LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011Thesimpledatatypesrepresentasinglepieceofinformation:forexample,asinglenumberorasinglesequenceoftext.
However,mostofthedatatypesdefinedinActionScriptcouldarecomplexdatatypes.
Theyrepresentasetofvaluesinasinglecontainer.
Forexample,avariablewiththedatatypeDaterepresentsasinglevalue(amomentintime).
Nevertheless,thatdatevalueisrepresentedasseveralvalues:theday,month,year,hours,minutes,seconds,andsoon,allofwhichareindividualnumbers.
Peoplegenerallythinkofadateasasinglevalue,andyoucantreatadateasasinglevaluebycreatingaDatevariable.
However,internallythecomputerthinksofitasagroupofseveralvaluesthat,puttogether,defineasingledate.
Mostofthebuilt-indatatypes,aswellasdatatypesdefinedbyprogrammers,arecomplexdatatypes.
Someofthecomplexdatatypesyouprobablyrecognizeare:MovieClip:amovieclipsymbolTextField:adynamicorinputtextfieldSimpleButton:abuttonsymbolDate:informationaboutasinglemomentintime(adateandtime)Twowordsthatareoftenusedassynonymsfordatatypeareclassandobject.
Aclassissimplythedefinitionofadatatype.
It'slikeatemplateforallobjectsofthedatatype,likesaying"allvariablesoftheExampledatatypehavethesecharacteristics:A,B,andC.
"Anobject,ontheotherhand,isjustanactualinstanceofaclass.
Forexample,avariablewhosedatatypeisMovieClipcouldbedescribedasaMovieClipobject.
Thefollowingaredifferentwaysofsayingthesamething:ThedatatypeofthevariablemyVariableisNumber.
ThevariablemyVariableisaNumberinstance.
ThevariablemyVariableisaNumberobject.
ThevariablemyVariableisaninstanceoftheNumberclass.
WorkingwithobjectsActionScriptiswhat'sknownasanobject-orientedprogramminglanguage.
Object-orientedprogrammingissimplyanapproachtoprogramming.
It'sreallynothingmorethanawaytoorganizethecodeinaprogram,usingobjects.
Earliertheterm"computerprogram"wasdefinedasaseriesofstepsorinstructionsthatthecomputerperforms.
Conceptually,then,youcanimagineacomputerprogramasjustasinglelonglistofinstructions.
However,inobject-orientedprogramming,theprograminstructionsaredividedamongdifferentobjects.
Thecodeisgroupedintochunksoffunctionality,sorelatedtypesoffunctionalityorrelatedpiecesofinformationaregroupedinonecontainer.
AdobeFlashProfessionalIfyou'veworkedwithsymbolsinFlashProfessional,you'realreadyusedtoworkingwithobjects.
Imagineyou'vedefinedamovieclipsymbolsuchasadrawingofarectangleandyou'veplacedacopyofitontheStage.
Thatmovieclipsymbolisalso(literally)anobjectinActionScript;it'saninstanceoftheMovieClipclass.
8LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011Therearevariouscharacteristicsofthemovieclipthatyoucanmodify.
Whenit'sselectedyoucanchangevaluesinthePropertyinspectorlikeitsxcoordinateoritswidth.
Youcanalsomakevariouscoloradjustmentslikechangingitsalpha(transparency)orapplyingadrop-shadowfiltertoit.
OtherFlashProfessionaltoolsletyoumakemorechanges,likeusingtheFreeTransformtooltorotatetherectangle.
AllofthesewaysthatyoucanmodifyamovieclipsymbolinFlashProfessionalarealsoavailableinActionScript.
YoumodifythemovieclipinActionScriptbychangingthepiecesofdatathatareallputtogetherintoasinglebundlecalledaMovieClipobject.
InActionScriptobject-orientedprogramming,therearethreetypesofcharacteristicsthatanyclasscaninclude:PropertiesMethodsEventsTheseelementsareusedtomanagethepiecesofdatausedbytheprogramandtodecidewhatactionsarecarriedoutandinwhatorder.
PropertiesApropertyrepresentsoneofthepiecesofdatathatarebundledtogetherinanobject.
Anexamplesongobjectcanhavepropertiesnamedartistandtitle;theMovieClipclasshaspropertieslikerotation,x,width,andalpha.
Youworkwithpropertieslikeindividualvariables.
Infact,youcanthinkofpropertiesassimplythe"child"variablescontainedinanobject.
HerearesomeexamplesofActionScriptcodethatusesproperties.
ThislineofcodemovestheMovieClipnamedsquaretothexcoordinate100pixels:square.
x=100;ThiscodeusestherotationpropertytomakethesquareMovieCliprotatetomatchtherotationofthetriangleMovieClip:square.
rotation=triangle.
rotation;ThiscodealtersthehorizontalscaleofthesquareMovieClipmakingitone-and-a-halftimeswiderthanitusedtobe:square.
scaleX=1.
5;Noticethecommonstructure:youuseavariable(square,triangle)asthenameoftheobject,followedbyaperiod(.
)andthenthenameoftheproperty(x,rotation,scaleX).
Theperiod,knownasthedotoperator,isusedtoindicatethatyou'reaccessingoneofthechildelementsofanobject.
Thewholestructuretogether,"variablename-dot-propertyname,"isusedlikeasinglevariable,asanameforasinglevalueinthecomputer'smemory.
MethodsAmethodisanactionthatanobjectcanperform.
Forexample,supposeyou'vemadeamovieclipsymbolinFlashProfessionalwithseveralkeyframesandanimationonitstimeline.
Thatmovieclipcanplay,orstop,orbeinstructedtomovetheplayheadtoaparticularframe.
ThiscodeinstructstheMovieClipnamedshortFilmtostartplaying:shortFilm.
play();ThislinemakestheMovieClipnamedshortFilmstopplaying(theplayheadstopsinplace,likepausingavideo):shortFilm.
stop();9LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011ThiscodemakesaMovieClipnamedshortFilmmoveitsplayheadtoFrame1andstopplaying(likerewindingavideo):shortFilm.
gotoAndStop(1);Methods,likeproperties,areaccessedbywritingtheobject'sname(avariable),thenaperiod,andthenthenameofthemethodfollowedbyparentheses.
Theparenthesesarethewaythatyouindicatethatyouarecallingthemethod,orinotherwords,instructingtheobjecttoperformthataction.
Sometimesvalues(orvariables)areplacedintheparentheses,asawaytopassalongadditionalinformationthatisnecessarytocarryouttheaction.
Thesevaluesareknownasmethodparameters.
Forexample,thegotoAndStop()methodneedsinformationaboutwhichframetogoto,soitrequiresasingleparameterintheparentheses.
Othermethods,likeplay()andstop(),areself-explanatory,sotheydon'trequireextrainformation.
Nevertheless,theyarestillwrittenwithparentheses.
Unlikeproperties(andvariables),methodsaren'tusedasvalueplaceholders.
However,somemethodscanperformcalculationsandreturnaresultthatcanbeusedlikeavariable.
Forexample,theNumberclass'stoString()methodconvertsthenumericvaluetoitstextrepresentation:varnumericData:Number=9;vartextData:String=numericData.
toString();Forexample,youwouldusethetoString()methodifyouwantedtodisplaythevalueofaNumbervariableinatextfieldonthescreen.
TheTextFieldclass'stextpropertyisdefinedasaString,soitcancontainonlytextvalues.
(Thetextpropertyrepresentstheactualtextcontentdisplayedonthescreen).
ThislineofcodeconvertsthenumericvalueinthevariablenumericDatatotext.
ItthenmakesthevalueshowuponthescreenintheTextFieldobjectnamedcalculatorDisplay:calculatorDisplay.
text=numericData.
toString();EventsAcomputerprogramisaseriesofinstructionsthatthecomputercarriesoutstep-by-step.
Somesimplecomputerprogramsconsistofnothingmorethanafewstepsthatthecomputerperforms,atwhichpointtheprogramends.
However,ActionScriptprogramsaredesignedtokeeprunning,waitingforuserinputorotherthingstohappen.
Eventsarethemechanismthatdetermineswhichinstructionsthecomputercarriesoutandwhen.
Inessence,eventsarethingsthathappenthatActionScriptisawareofandcanrespondto.
Manyeventsarerelatedtouserinteraction,suchasauserclickingabuttonorpressingakeyonthekeyboard.
Therearealsoothertypesofevents.
Forexample,ifyouuseActionScripttoloadanexternalimage,thereisaneventthatcanletyouknowwhentheimagehasfinishedloading.
WhenanActionScriptprogramisrunning,conceptuallyitjustsitsandwaitsforcertainthingstohappen.
Whenthosethingshappen,thespecificActionScriptcodethatyou'vespecifiedforthoseeventsruns.
BasiceventhandlingThetechniqueforspecifyingcertainactionstoperforminresponsetoparticulareventsisknownaseventhandling.
WhenyouarewritingActionScriptcodetoperformeventhandling,therearethreeimportantelementsyou'llwanttoidentify:Theeventsource:WhichobjectistheonetheeventisgoingtohappentoForexample,whichbuttonwasclicked,orwhichLoaderobjectisloadingtheimageTheeventsourceisalsoknownastheeventtarget.
Ithasthisnamebecauseit'stheobjectwherethecomputertargetstheevent(thatis,wheretheeventactuallyhappens).
Theevent:Whatisthethingthatisgoingtohappen,thethingthatyouwanttorespondtoThespecificeventisimportanttoidentify,becausemanyobjectstriggerseveralevents.
Theresponse:Whatstepsdoyouwantperformedwhentheeventhappens10LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011AnytimeyouwriteActionScriptcodetohandleevents,itrequiresthesethreeelements.
Thecodefollowsthisbasicstructure(elementsinboldareplaceholdersyou'dfillinforyourspecificcase):functioneventResponse(eventObject:EventType):void{//Actionsperformedinresponsetotheeventgohere.
}eventSource.
addEventListener(EventType.
EVENT_NAME,eventResponse);Thiscodedoestwothings.
First,itdefinesafunction,whichisthewaytospecifytheactionsyouwantperformedinresponsetotheevent.
Next,itcallstheaddEventListener()methodofthesourceobject.
CallingaddEventListener()essentially"subscribes"thefunctiontothespecifiedevent.
Whentheeventhappens,thefunction'sactionsarecarriedout.
Considereachofthesepartsinmoredetail.
Afunctionprovidesawayforyoutogroupactionswithasinglenamethatislikeashortcutnametocarryouttheactions.
Afunctionisidenticaltoamethodexceptthatitisn'tnecessarilyassociatedwithaspecificclass.
(Infact,theterm"method"couldbedefinedasafunctionthatisassociatedwithaparticularclass.
)Whenyou'recreatingafunctionforeventhandling,youchoosethenameforthefunction(namedeventResponseinthiscase).
Youalsospecifyoneparameter(namedeventObjectinthisexample).
Specifyingafunctionparameterislikedeclaringavariable,soyoualsohavetoindicatethedatatypeoftheparameter.
(Inthisexample,theparameter'sdatatypeisEventType.
)EachtypeofeventthatyouwanttolistentohasanActionScriptclassassociatedwithit.
Thedatatypeyouspecifyforthefunctionparameterisalwaystheassociatedclassofthespecificeventyouwanttorespondto.
Forexample,aclickevent(triggeredwhentheuserclicksanitemwiththemouse)isassociatedwiththeMouseEventclass.
Towritealistenerfunctionforaclickevent,youdefinethelistenerfunctionwithaparameterwiththedatatypeMouseEvent.
Finally,betweentheopeningandclosingcurlybracketsyouwritetheinstructionsyouwantthecomputertocarryoutwhentheeventhappens.
Theevent-handlingfunctioniswritten.
Nextyoutelltheeventsourceobject(theobjectthattheeventhappensto,forexamplethebutton)thatyouwantittocallyourfunctionwhentheeventhappens.
YouregisteryourfunctionwiththeeventsourceobjectbycallingtheaddEventListener()methodofthatobject(allobjectsthathaveeventsalsohaveanaddEventListener()method).
TheaddEventListener()methodtakestwoparameters:First,thenameofthespecificeventyouwanttorespondto.
Eacheventisaffiliatedwithaspecificclass.
Everyeventclasshasaspecialvalue,whichislikeauniquename,definedforeachofitsevents.
Youusethatvalueforthefirstparameter.
Second,thenameofyoureventresponsefunction.
Notethatafunctionnameiswrittenwithoutparentheseswhenit'spassedasaparameter.
Theevent-handlingprocessThefollowingisastep-by-stepdescriptionoftheprocessthathappenswhenyoucreateaneventlistener.
Inthiscase,it'sanexampleofcreatingalistenerfunctionthatiscalledwhenanobjectnamedmyButtonisclicked.
Theactualcodewrittenbytheprogrammerisasfollows:functioneventResponse(event:MouseEvent):void{//Actionsperformedinresponsetotheeventgohere.
}myButton.
addEventListener(MouseEvent.
CLICK,eventResponse);11LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011Hereishowthiscodewouldactuallyworkwhenit'srunning:1WhentheSWFfileloads,thecomputermakesnoteofthefactthatthere'safunctionnamedeventResponse().
2Thecomputerthenrunsthecode(specifically,thelinesofcodethataren'tinafunction).
Inthiscasethat'sonlyonelineofcode:callingtheaddEventListener()methodontheeventsourceobject(namedmyButton)andpassingtheeventResponsefunctionasaparameter.
Internally,myButtonkeepsalistoffunctionsthatarelisteningtoeachofitsevents.
WhenitsaddEventListener()methodiscalled,myButtonstorestheeventResponse()functioninitslistofeventlisteners.
12LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/20113Atsomepoint,theuserclicksthemyButtonobject,triggeringitsclickevent(identifiedasMouseEvent.
CLICKinthecode).
Atthatpoint,thefollowingoccurs:aAnobjectiscreatedthat'saninstanceoftheclassassociatedwiththeeventinquestion(MouseEventinthisexample).
Formanyevents,thisobjectisaninstanceoftheEventclass.
Formouseevents,itisaMouseEventinstance.
Forotherevents,itisaninstanceoftheclassthat'sassociatedwiththatevent.
Thisobjectthat'screatedisknownastheeventobject,anditcontainsspecificinformationabouttheeventthathappened:whattypeofeventitis,whereithappened,andotherevent-specificinformationifapplicable.
bThecomputerthenlooksatthelistofeventlistenersstoredbymyButton.
Itgoesthroughthesefunctionsonebyone,callingeachfunctionandpassingtheeventobjecttothefunctionasaparameter.
SincetheeventResponse()functionisoneofmyButton'slisteners,aspartofthisprocessthecomputercallstheeventResponse()function.
13LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011cWhentheeventResponse()functioniscalled,thecodeinthatfunctionruns,soyourspecifiedactionsarecarriedout.
Event-handlingexamplesHereareafewmoreconcreteexamplesofeventhandlingcode.
Theseexamplesaremeanttogiveyouanideaofsomeofthecommoneventelementsandpossiblevariationsavailablewhenyouwriteevent-handlingcode:Clickingabuttontostartthecurrentmovieclipplaying.
Inthefollowingexample,playButtonistheinstancenameofthebutton,andthisisaspecialnamemeaning"thecurrentobject":this.
stop();functionplayMovie(event:MouseEvent):void{this.
play();}playButton.
addEventListener(MouseEvent.
CLICK,playMovie);Detectingtypinginatextfield.
Inthisexample,entryTextisaninputtextfield,andoutputTextisadynamictextfield:functionupdateOutput(event:TextEvent):void{varpressedKey:String=event.
text;outputText.
text="Youtyped:"+pressedKey;}entryText.
addEventListener(TextEvent.
TEXT_INPUT,updateOutput);ClickingabuttontonavigatetoaURL.
Inthiscase,linkButtonistheinstancenameofthebutton:functiongotoAdobeSite(event:MouseEvent):void{varadobeURL:URLRequest=newURLRequest("http://www.
adobe.
com/");navigateToURL(adobeURL);}linkButton.
addEventListener(MouseEvent.
CLICK,gotoAdobeSite);14LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011CreatingobjectinstancesBeforeyoucanuseanobjectinActionScript,theobjecthastoexistinthefirstplace.
Onepartofcreatinganobjectisdeclaringavariable;however,declaringavariableonlycreatesanemptyplaceinthecomputer'smemory.
Alwaysassignanactualvaluetothevariable(createanobjectandstoreitinthevariable)beforeyouattempttouseormanipulateit.
Theprocessofcreatinganobjectisknownasinstantiatingtheobject.
Inotherwords,youcreateaninstanceofaparticularclass.
Onesimplewaytocreateanobjectinstancedoesn'tinvolveActionScriptatall.
InFlashProfessionalplaceamovieclipsymbol,buttonsymbol,ortextfieldontheStageandassignitaninstancename.
FlashProfessionalautomaticallydeclaresavariablewiththatinstancename,createsanobjectinstance,andstoresthatobjectinthevariable.
Similarly,inFlexyoucreateacomponentinMXMLeitherbycodinganMXMLtagorbyplacingthecomponentontheeditorinFlashBuilderDesignmode.
WhenyouassignanIDtothatcomponent,thatIDbecomesthenameofanActionScriptvariablecontainingthatcomponentinstance.
However,youdon'talwayswanttocreateanobjectvisually,andfornon-visualobjectsyoucan't.
ThereareseveraladditionalwaysyoucancreateobjectinstancesusingonlyActionScript.
WithseveralActionScriptdatatypes,youcancreateaninstanceusingaliteralexpression,whichisavaluewrittendirectlyintotheActionScriptcode.
Herearesomeexamples:Literalnumericvalue(enterthenumberdirectly):varsomeNumber:Number=17.
239;varsomeNegativeInteger:int=-53;varsomeUint:uint=22;LiteralStringvalue(surroundthetextwithdoublequotationmarks):varfirstName:String="George";varsoliloquy:String="Tobeornottobe,thatisthequestion.
.
.
";LiteralBooleanvalue(usetheliteralvaluestrueorfalse):varniceWeather:Boolean=true;varplayingOutside:Boolean=false;LiteralArrayvalue(wrapacomma-separatedlistofvaluesinsquarebrackets):varseasons:Array=["spring","summer","autumn","winter"];LiteralXMLvalue(entertheXMLdirectly):varemployee:XML=HaroldWebster;ActionScriptalsodefinesliteralexpressionsfortheArray,RegExp,Object,andFunctiondatatypes.
Themostcommonwaytocreateaninstanceforanydatatypeistousethenewoperatorwiththeclassname,asshownhere:varraceCar:MovieClip=newMovieClip();varbirthday:Date=newDate(2006,7,9);Creatinganobjectusingthenewoperatorisoftendescribedas"callingtheclass'sconstructor.
"Aconstructorisaspecialmethodthatiscalledaspartoftheprocessofcreatinganinstanceofaclass.
Noticethatwhenyoucreateaninstanceinthisway,youputparenthesesaftertheclassname.
Sometimesyouspecifyparametervaluesintheparentheses.
Thesearetwothingsthatyoualsodowhencallingamethod.
Evenforthosedatatypesthatletyoucreateinstancesusingaliteralexpression,youcanalsousethenewoperatortocreateanobjectinstance.
Forexample,thesetwolinesofcodedothesamething:15LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011varsomeNumber:Number=6.
33;varsomeNumber:Number=newNumber(6.
33);It'simportanttobefamiliarwiththenewClassName()wayofcreatingobjects.
ManyActionScriptdatatypesdon'thaveavisualrepresentation.
Consequently,theycan'tbecreatedbyplacinganitemontheFlashProfessionalStageortheDesignmodeofFlashBuilder'sMXMLeditor.
YoucanonlycreateaninstanceofanyofthosedatatypesinActionScriptusingthenewoperator.
AdobeFlashProfessionalInFlashProfessional,thenewoperatorcanalsobeusedtocreateaninstanceofamovieclipsymbolthatisdefinedintheLibrarybutisn'tplacedontheStage.
MoreHelptopicsWorkingwitharraysUsingregularexpressionsCreatingMovieClipobjectswithActionScriptCommonprogramelementsThereareafewadditionalbuildingblocksthatyouusetocreateanActionScriptprogram.
OperatorsOperatorsarespecialsymbols(oroccasionallywords)thatareusedtoperformcalculations.
Theyaremostlyusedformathoperations,andalsousedwhencomparingvaluestoeachother.
Generally,anoperatorusesoneormorevaluesand"worksout"toasingleresult.
Forexample:Theadditionoperator(+)addstwovaluestogether,resultinginasinglenumber:varsum:Number=23+32;Themultiplicationoperator(*)multipliesonevaluebyanother,resultinginasinglenumber:varenergy:Number=mass*speedOfLight*speedOfLight;Theequalityoperator(==)comparestwovaluestoseeiftheyareequal,resultinginasingletrue-or-false(Boolean)value:if(dayOfWeek=="Wednesday"){takeOutTrash();}Asshownhere,theequalityoperatorandtheother"comparison"operatorsaremostcommonlyusedwiththeifstatementtodeterminewhetherornotcertaininstructionsarecarriedout.
16LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011CommentsAsyou'rewritingActionScript,you'lloftenwanttoleavenotestoyourself.
Forexample,sometimesyouwanttoexplainhowcertainlinesofcodeworkorwhyyoumadeaparticularchoice.
Codecommentsareatoolyoucanusetowritetextthatthecomputerignoresinyourcode.
ActionScriptincludestwokindsofcomments:Single-linecomment:Asingle-linecommentisdesignatedbyplacingtwoslashesanywhereonaline.
Thecomputerignoreseverythingaftertheslashesuptotheendofthatline://Thisisacomment;it'signoredbythecomputer.
varage:Number=10;//Settheageto10bydefault.
Multilinecomments:Amultilinecommentincludesastartingcommentmarker(/*),thenthecommentcontent,andanendingcommentmarker(*/).
Thecomputerignoreseverythingbetweenthestartingandendingmarkersregardlessofhowmanylinesthecommentspans:/*Thisisalongdescriptionexplainingwhataparticularfunctionisusedfororexplainingasectionofcode.
Inanycase,thecomputerignorestheselines.
*/Anothercommonuseofcommentsistotemporarily"turnoff"oneormorelinesofcode.
Forexample,youcanusecommentsifyou'retestingoutadifferentwayofdoingsomething.
YoucanalsousethemtotrytofigureoutwhycertainActionScriptcodeisn'tworkingthewayyouexpect.
FlowcontrolManytimesinaprogram,youwanttorepeatcertainactions,performonlycertainactionsandnotothers,performalternativeactionsdependingoncertainconditions,andsoon.
Flowcontrolisthecontroloverwhichactionsareperformed.
ThereareseveraltypesofflowcontrolelementsavailableinActionScript.
Functions:Functionsarelikeshortcuts.
Theyprovideawaytogroupaseriesofactionsunderasinglename,andcanbeusedtoperformcalculations.
Functionsarenecessaryforhandlingevents,butarealsousedasageneraltoolforgroupingaseriesofinstructions.
Loops:Loopstructuresletyoudesignateasetofinstructionsthatthecomputerperformsasetnumberoftimesoruntilsomeconditionchanges.
Oftenloopsareusedtomanipulateseveralrelateditems,usingavariablewhosevaluechangeseachtimethecomputerworksthroughtheloop.
Conditionalstatements:Conditionalstatementsprovideawaytodesignatecertaininstructionsthatarecarriedoutonlyundercertaincircumstances.
Theyarealsousedtoprovidealternativesetsofinstructionsfordifferentconditions.
Themostcommontypeofconditionalstatementistheifstatement.
Theifstatementchecksavalueorexpressioninitsparentheses.
Ifthevalueistrue,thelinesofcodeincurlybracketsarecarriedout.
Otherwise,theyareignored.
Forexample:if(age3.
0GettingstartedwithActionScriptLastupdated5/2/2011if(username=="admin"){//dosomeadministrator-onlythings,likeshowingextraoptions}else{//dosomenon-administratorthings}Example:Animationportfoliopiece(FlashProfessional)ThisexampleisdesignedtogiveyouafirstopportunitytoseehowyoucanpiecetogetherbitsofActionScriptintoacompleteapplication.
Theanimationportfoliopieceisanexampleofhowyoucouldtakeanexistinglinearanimationandaddsomeminorinteractiveelements.
Forexample,youcouldincorporateananimationcreatedforaclientintoanonlineportfolio.
Theinteractivebehaviorthatyou'lladdtotheanimationincludestwobuttonstheviewercanclick:onetostarttheanimation,andonetonavigatetoaseparateURL(suchastheportfoliomenuortheauthor'shomepage).
Theprocessofcreatingthispiececanbedividedintothesemainsections:1PreparetheFLAfileforaddingActionScriptandinteractiveelements.
2Createandaddthebuttons.
3WritetheActionScriptcode.
4Testtheapplication.
PreparingtoaddinteractivityBeforeyoucanaddinteractiveelementstoyouranimation,it'shelpfultosetuptheFLAfilebycreatingsomeplacestoaddyournewcontent.
ThistaskincludescreatingactualspaceontheStagewherebuttonscanbeplaced.
Italsoincludescreating"space"intheFLAfileforkeepingdifferentitemsseparate.
TosetupyourFLAforaddinginteractiveelements:1CreateaFLAfilewithasimpleanimationsuchasasinglemotiontweenorshapetween.
IfyoualreadyhaveaFLAfilecontainingtheanimationthatyou'reshowcasingintheproject,openthatfileandsaveitwithanewname.
2Decidewhereonthescreenyou'llwantthetwobuttonstoappear.
Onebuttonistostarttheanimationandoneistolinktotheauthorportfolioorhomepage.
Ifnecessary,clearoraddsomespaceontheStageforthisnewcontent.
Iftheanimationdoesn'talreadyhaveone,youcancreateastartupscreenonthefirstframe.
Inthatcaseyou'llprobablywanttoshifttheanimationoversoitstartsonFrame2orlater.
3Addanewlayer,abovetheotherlayersintheTimeline,andnameitbuttons.
Thislayeriswhereyou'lladdthebuttons.
4Addanewlayer,abovethebuttonslayer,andnameitactions.
Thislayeriswhereyou'lladdActionScriptcodetoyourapplication.
CreatingandaddingbuttonsNext,you'llactuallycreateandpositionthebuttonsthatformthecenteroftheinteractiveapplication.
18LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011TocreateandaddbuttonstotheFLA:1Usingthedrawingtools,createthevisualappearanceofyourfirstbutton(the"play"button)onthebuttonslayer.
Forexample,drawahorizontalovalwithtextontopofit.
2UsingtheSelectiontool,selectallthegraphicpartsofthesinglebutton.
3Fromthemainmenu,chooseModify>ConvertToSymbol.
4Inthedialogbox,chooseButtonasthesymboltype,givethesymbolaname,andclickOK.
5Withthebuttonselected,inthePropertyinspectorgivethebuttontheinstancenameplayButton.
6Repeatsteps1through5tocreatethebuttonthattakestheviewertotheauthor'shomepage.
NamethisbuttonhomeButton.
WritingthecodeTheActionScriptcodeforthisapplicationcanbedividedintothreesetsoffunctionality,althoughyouenteritallinthesameplace.
Thethreethingsthecodedoesare:StoptheplayheadassoonastheSWFfileloads(whentheplayheadentersFrame1).
ListenforaneventtostarttheSWFfileplayingwhentheuserclickstheplaybutton.
ListenforaneventtosendthebrowsertotheappropriateURLwhentheuserclickstheauthorhomepagebutton.
TocreatecodetostoptheplayheadwhenitentersFrame1:1SelectthekeyframeonFrame1oftheactionslayer.
2ToopentheActionspanel,fromthemainmenu,chooseWindow>Actions.
3IntheScriptpane,enterthefollowingcode:stop();Towritecodetostarttheanimationwhentheplaybuttonisclicked:1Attheendofthecodeenteredintheprevioussteps,addtwoemptylines.
2Enterthefollowingcodeatthebottomofthescript:functionstartMovie(event:MouseEvent):void{this.
play();}ThiscodedefinesafunctioncalledstartMovie().
WhenstartMovie()iscalled,itcausesthemaintimelinetostartplaying.
3Onthelinefollowingthecodeaddedinthepreviousstep,enterthislineofcode:playButton.
addEventListener(MouseEvent.
CLICK,startMovie);ThislineofcoderegistersthestartMovie()functionasalistenerforplayButton'sclickevent.
Inotherwords,itmakesitsothatwheneverthebuttonnamedplayButtonisclicked,thestartMovie()functioniscalled.
TowritecodetosendthebrowsertoaURLwhenthehomepagebuttonisclicked:1Attheendofthecodeenteredintheprevioussteps,addtwoemptylines.
2Enterthiscodeatthebottomofthescript:19LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011functiongotoAuthorPage(event:MouseEvent):void{vartargetURL:URLRequest=newURLRequest("http://example.
com/");navigateToURL(targetURL);}ThiscodedefinesafunctioncalledgotoAuthorPage().
ThisfunctionfirstcreatesaURLRequestinstancerepresentingtheURLhttp://example.
com/.
ItthenpassesthatURLtothenavigateToURL()function,causingtheuser'sbrowsertoopenthatURL.
3Onthelinefollowingthecodeaddedinthepreviousstep,enterthislineofcode:homeButton.
addEventListener(MouseEvent.
CLICK,gotoAuthorPage);ThislineofcoderegistersthegotoAuthorPage()functionasalistenerforhomeButton'sclickevent.
Inotherwords,itmakesitsothatwheneverthebuttonnamedhomeButtonisclicked,thegotoAuthorPage()functioniscalled.
TestingtheapplicationTheapplicationisnowcompletelyfunctional.
Let'stestittomakesurethat'sthecase.
Totesttheapplication:1Fromthemainmenu,chooseControl>TestMovie.
FlashProfessionalcreatestheSWFfileandopensitinaFlashPlayerwindow.
2Tryboththebuttonstomakesurethattheydowhatyouexpectthemto.
3Ifthebuttonsdon'twork,herearesomethingstocheckfor:DothebuttonsbothhavedistinctinstancenamesDotheaddEventListener()methodcallsusethesamenamesasthebuttons'instancenamesArethecorrecteventnamesusedintheaddEventListener()methodcallsIsthecorrectparameterspecifiedforeachofthefunctions(BothmethodsneedasingleparameterwiththedatatypeMouseEvent.
)Allofthesemistakesandmostotherpossiblemistakesresultinanerrormessage.
TheerrormessagecanappeareitherwhenyouchoosetheTestMoviecommandorwhenyouclickthebuttonwhiletestingtheproject.
LookintheCompilerErrorspanelforcompilererrors(theonesthathappenwhenyoufirstchooseTestMovie).
ChecktheOutputpanelforrun-timeerrorswhichhappenwhilethecontentisplaying,suchaswhenyouclickabutton.
BuildingapplicationswithActionScriptTheprocessofwritingActionScripttobuildanapplicationinvolvesmorethanjustknowingthesyntaxandthenamesoftheclassesyou'lluse.
MostoftheFlashPlatformdocumentationcoversthosetwotopics(syntaxandusingActionScriptclasses).
However,tobuildanActionScriptapplicationyou'llalsowanttoknowinformationsuchas:WhatprogramscanbeusedforwritingActionScriptHowdoyouorganizeActionScriptcodeHowdoyouincludeActionScriptcodeinanapplicationWhatstepsdoyoufollowindevelopinganActionScriptapplication20LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011OptionsfororganizingyourcodeYoucanuseActionScript3.
0codetopowereverythingfromsimplegraphicsanimationstocomplexclient-servertransactionprocessingsystems.
Dependingonthetypeofapplicationyou'rebuilding,useoneormoreofthesedifferentwaysofincludingActionScriptinyourproject.
StoringcodeinframesinaFlashProfessionaltimelineInFlashProfessional,youcanaddActionScriptcodetoanyframeinatimeline.
Thiscodeexecuteswhilethemovieisplayingback,whentheplayheadentersthatframe.
PlacingActionScriptcodeinframesprovidesasimplewaytoaddbehaviorstoapplicationsbuiltinFlashProfessional.
YoucanaddcodetoanyframeinthemaintimelineortoanyframeinthetimelineofanyMovieClipsymbol.
However,thisflexibilitycomeswithacost.
Whenyoubuildlargerapplications,itbecomeseasytolosetrackofwhichframescontainwhichscripts.
Thiscomplicatedstructurecanmaketheapplicationmoredifficulttomaintainovertime.
ManydeveloperssimplifytheorganizationoftheirActionScriptcodeintheFlashProfessionalbyplacingcodeonlyinthefirstframeofatimelineoronaspecificlayerintheFlashdocument.
SeparatingyourcodemakesiteasiertolocateandmaintainthecodeinyourFlashFLAfiles.
However,thesamecodecan'tbeusedinanotherFlashProfessionalprojectwithoutcopyingandpastingthecodeintothenewfile.
TomakeiteasiertouseyourActionScriptcodeinotherFlashProfessionalprojectsinthefuture,storeyourcodeinexternalActionScriptfiles(textfileswiththe.
asextension).
EmbeddingcodeinFlexMXMLfilesInaFlexdevelopmentenvironmentsuchasFlashBuilder,youcanincludeActionScriptcodeinsideantaginaFlexMXMLfile.
However,thistechniquecanaddcomplexitytolargeprojectsandmakeitmoredifficulttousethesamecodeinanotherFlexproject.
TomakeiteasiertouseyourActionScriptcodeinotherFlexprojectsinthefuture,storeyourcodeinexternalActionScriptfiles.
Note:Youcanspecifyasourceparameterforantag.
Usingasourceparameterletsyou"import"ActionScriptcodefromanexternalfileasifitwastypeddirectlywithinthetag.
However,thesourcefilethatyouusecannotdefineitsownclass,whichlimitsitsreusability.
StoringcodeinActionScriptfilesIfyourprojectinvolvessignificantActionScriptcode,thebestwaytoorganizeyourcodeisinseparateActionScriptsourcefiles(textfileswiththe.
asextension).
AnActionScriptfilecanbestructuredinoneoftwoways,dependingonhowyouintendtouseitinyourapplication.
UnstructuredActionScriptcode:LinesofActionScriptcode,includingstatementsorfunctiondefinitions,writtenasthoughtheywereentereddirectlyinatimelinescriptorMXMLfile.
ActionScriptwritteninthiswaycanbeaccessedusingtheincludestatementinActionScript,orthetaginFlexMXML.
TheActionScriptincludestatementtellsthecompilertoincludethecontentsofanexternalActionScriptfileataspecificlocationandwithinagivenscopeinascript.
Theresultisthesameasifthecodewereenteredtheredirectly.
IntheMXMLlanguage,usingantagwithasourceattributeidentifiesanexternalActionScriptthatthecompilerloadsatthatpointintheapplication.
Forexample,thefollowingtagloadsanexternalActionScriptfilenamedBox.
as:ActionScriptclassdefinition:AdefinitionofanActionScriptclass,includingitsmethodandpropertydefinitions.
21LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011WhenyoudefineaclassyoucanaccesstheActionScriptcodeintheclassbycreatinganinstanceoftheclassandusingitsproperties,methods,andevents.
Usingyourownclassesisidenticaltousinganyofthebuilt-inActionScriptclasses,andrequirestwoparts:Usetheimportstatementtospecifythefullnameoftheclass,sotheActionScriptcompilerknowswheretofindit.
Forexample,tousetheMovieClipclassinActionScript,importtheclassusingitsfullname,includingpackageandclass:importflash.
display.
MovieClip;Alternatively,youcanimportthepackagethatcontainstheMovieClipclass,whichisequivalenttowritingseparateimportstatementsforeachclassinthepackage:importflash.
display.
*;Thetop-levelclassesaretheonlyexceptiontotherulethataclassmustbeimportedtousethatclassinyourcode.
Thoseclassesarenotdefinedinapackage.
Writecodethatspecificallyusestheclassname.
Forexample,declareavariablewiththatclassasitsdatatypeandcreateaninstanceoftheclasstostoreinthevariable.
ByusingaclassinActionScriptcode,youtellthecompilertoloadthedefinitionofthatclass.
Forexample,givenanexternalclasscalledBox,thisstatementcreatesaninstanceoftheBoxclass:varsmallBox:Box=newBox(10,20);ThefirsttimethecompilercomesacrossthereferencetotheBoxclassitsearchestheavailablesourcecodetolocatetheBoxclassdefinition.
ChoosingtherighttoolYoucanuseoneofseveraltools(ormultipletoolstogether)forwritingandeditingyourActionScriptcode.
FlashBuilderAdobeFlashBuilderisthepremiertoolforcreatingprojectswiththeFlexframeworkorprojectsthatprimarilyconsistofActionScriptcode.
FlashBuilderalsoincludesafull-featuredActionScripteditoraswellasvisuallayoutandMXMLeditingcapabilities.
ItcanbeusedtocreateFlexorActionScript-onlyprojects.
Flexprovidesseveralbenefitsincludingarichsetofpre-builtuserinterfacecontrols,flexibledynamiclayoutcontrols,andbuilt-inmechanismsforworkingwithremotedataandlinkingexternaldatatouserinterfaceelements.
However,becauseoftheadditionalcoderequiredtoprovidethesefeatures,projectsthatuseFlexcanhavealargerSWFfilesizethantheirnon-Flexcounterparts.
UseFlashBuilderifyouarecreatingfull-featureddata-drivenrichInternetapplicationswithFlex.
UseitwhenyouwanttoeditActionScriptcode,editMXMLcode,andlayoutyourapplicationvisually,allwithinasingletool.
ManyFlashProfessionaluserswhobuildActionScript-heavyprojectsuseFlashProfessionaltocreatevisualassetsandFlashBuilderasaneditorforActionScriptcode.
FlashProfessionalInadditiontoitsgraphicsandanimationcreationcapabilities,FlashProfessionalincludestoolsforworkingwithActionScriptcode.
ThecodecaneitherbeattachedtoelementsinaFLAfileorinexternalActionScript-onlyfiles.
FlashProfessionalisidealforprojectsthatinvolvesignificantanimationorvideo.
Itisvaluablewhenyouwanttocreatemostofthegraphicassetsyourself.
AnotherreasontouseFlashProfessionaltodevelopyourActionScriptprojectistocreatevisualassetsandwritecodeinthesameapplication.
FlashProfessionalalsoincludespre-builtuserinterfacecomponents.
YoucanusethosecomponentstoachievesmallerSWFfilesizeandusevisualtoolstoskinthemforyourproject.
22LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011FlashProfessionalincludestwotoolsforwritingActionScriptcode:Actionspanel:AvailablewhenworkinginaFLAfile,thispanelallowsyoutowriteActionScriptcodeattachedtoframesonatimeline.
Scriptwindow:TheScriptwindowisadedicatedtexteditorforworkingwithActionScript(.
as)codefiles.
Third-partyActionScripteditorBecauseActionScript(.
as)filesarestoredassimpletextfiles,anyprogramthatcaneditplaintextfilescanbeusedtowriteActionScriptfiles.
InadditiontoAdobe'sActionScriptproducts,severalthird-partytexteditingprogramswithActionScript-specificcapabilitieshavebeencreated.
YoucanwriteanMXMLfileorActionScriptclassesusinganytexteditorprogram.
YoucanthencreateanapplicationfromthosefilesusingtheFlexSDK.
TheprojectcanuseFlexorbeanActionScript-onlyapplication.
Alternatively,somedevelopersuseFlashBuilderorathird-partyActionScripteditorforwritingActionScriptclasses,incombinationwithFlashProfessionalforcreatinggraphicalcontent.
Reasonstochooseathird-partyActionScripteditorinclude:YouprefertowriteActionScriptcodeinaseparateprogramanddesignvisualelementsinFlashProfessional.
Youuseanapplicationfornon-ActionScriptprogramming(suchascreatingHTMLpagesorbuildingapplicationsinanotherprogramminglanguage).
YouwanttousethesameapplicationforyourActionScriptcodingaswell.
YouwanttocreateActionScript-onlyorFlexprojectsusingtheFlexSDKwithoutFlashProfessionalorFlashBuilder.
SomeofthenotablecodeeditorsprovidingActionScript-specificsupportinclude:AdobeDreamweaverCS4ASDTFDTFlashDevelopPrimalScriptSE|PYTextMate(withActionScriptandFlexbundles)TheActionScriptdevelopmentprocessWhetheryourActionScriptprojectislargeorsmall,usingaprocesstodesignanddevelopyourapplicationmakesworkmoreefficientandeffective.
ThefollowingstepsdescribeabasicdevelopmentprocessforbuildinganapplicationthatusesActionScript3.
0:1Designyourapplication.
Describeyourapplicationinsomewaybeforeyoustartbuildingit.
2ComposeyourActionScript3.
0code.
YoucancreateActionScriptcodeusingFlashProfessional,FlashBuilder,Dreamweaver,oratexteditor.
3CreateaFlashorFlexprojecttorunyourcode.
InFlashProfessional,createaFLAfile,setupthepublishsettings,adduserinterfacecomponentstotheapplication,andreferencetheActionScriptcode.
InFlex,definetheapplication,adduserinterfacecomponentsusingMXML,andreferencetheActionScriptcode.
4PublishandtestyourActionScriptapplication.
23LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011Testingyourapplicationinvolvesrunningyourapplicationfromwithinyourdevelopmentenvironmentandmakingsurethatitdoeseverythingyouintended.
Youdon'tnecessarilyhavetofollowthesestepsinorder,orcompletelyfinishonestepbeforeworkingonanother.
Forexample,youcandesignonescreenofyourapplication(step1)andthencreatethegraphics,buttons,andsoon(step3)beforewritingActionScriptcode(step2)andtesting(step4).
Oryoucandesignpartofitandthenaddonebuttonorinterfaceelementatatime,writingActionScriptforeachoneandtestingitasit'sbuilt.
It'shelpfultorememberthesefourstagesofthedevelopmentprocess.
However,inreal-worlddevelopmentit'smoreeffectivetomovebackandforthamongthestagesasappropriate.
CreatingyourownclassesTheprocessofcreatingclassesforuseinyourprojectscanseemdaunting.
However,themoredifficultpartofcreatingaclassisthetaskofdesigningtheclass'smethods,properties,andevents.
StrategiesfordesigningaclassThetopicofobject-orienteddesignisacomplexone;entirecareershavebeendevotedtotheacademicstudyandprofessionalpracticeofthisdiscipline.
Nevertheless,hereareafewsuggestedapproachesthatcanhelpyougetstarted.
1Thinkabouttherolethattheinstancesofthisclassplayintheapplication.
Generally,objectsserveoneofthesethreeroles:Valueobject:Theseobjectsserveprimarilyascontainersofdata.
Theyprobablyhaveseveralpropertiesandfewermethods(orsometimesnomethods).
Theyaregenerallycoderepresentationsofclearlydefineditems.
Forexample,amusicplayerapplicationcouldincludeaSongclassrepresentingasinglereal-worldsongandaPlaylistclassrepresentingaconceptualgroupofsongs.
Displayobject:Theseareobjectsthatactuallyappearonthescreen.
Examplesincludeuser-interfaceelementslikeadrop-downlistorstatusreadout,graphicalelementslikecreaturesinavideogame,andsoon.
Applicationstructure:Theseobjectsplayabroadrangeofsupportingrolesinthelogicorprocessingperformedbyapplications.
Forexample,youcanmakeanobjecttoperformcertaincalculationsinabiologysimulation.
Youcanmakeonethat'sresponsibleforsynchronizingvaluesbetweenadialcontrolandavolumereadoutinamusicplayerapplication.
Anotheronecanmanagetherulesinavideogame.
Oryoucanmakeaclasstoloadasavedpictureinadrawingapplication.
2Decidethespecificfunctionalitythattheclassneeds.
Thedifferenttypesoffunctionalityoftenbecomethemethodsoftheclass.
3Iftheclassisintendedtoserveasavalueobject,decidethedatathattheinstancesinclude.
Theseitemsaregoodcandidatesforproperties.
4Sinceyourclassisbeingdesignedspecificallyforyourproject,what'smostimportantisthatyouprovidethefunctionalitythatyourapplicationneeds.
Trytoanswerthesequestionsforyourself:Whatpiecesofinformationisyourapplicationstoring,tracking,andmanipulatingAnsweringthisquestionhelpsyouidentifyanyvalueobjectsandpropertiesyouneed.
WhatsetsofactionsdoestheapplicationperformForexample,whathappenswhentheapplicationfirstloads,whenaparticularbuttonisclicked,whenamoviestopsplaying,andsoonThesearegoodcandidatesformethods.
Theycanalsobepropertiesifthe"actions"involvechangingindividualvalues.
Foranygivenaction,whatinformationisnecessarytoperformthatactionThosepiecesofinformationbecometheparametersofthemethod.
24LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011Astheapplicationproceedstodoitswork,whatthingschangeinyourclassthatotherpartsofyourapplicationneedtoknowaboutThesearegoodcandidatesforevents.
5Isthereisanexistingobjectthatissimilartotheobjectyouneedexceptthatit'slackingsomeadditionalfunctionalityyouwanttoaddConsidercreatingasubclass.
(Asubclassisaclasswhichbuildsonthefunctionalityofanexistingclass,ratherthandefiningallofitsownfunctionality.
)Forexample,tocreateaclassthatisavisualobjectonthescreen,usethebehaviorofanexistingdisplayobjectasabasisforyourclass.
Inthatcase,thedisplayobject(suchasMovieCliporSprite)wouldbethebaseclass,andyourclasswouldextendthatclass.
WritingthecodeforaclassOnceyouhaveadesignforyourclass,oratleastsomeideaofwhatinformationitstoresandwhatactionsitcarriesout,theactualsyntaxofwritingaclassisfairlystraightforward.
HerearetheminimumstepstocreateyourownActionScriptclass:1OpenanewtextdocumentinyourActionScripttexteditorprogram.
2Enteraclassstatementtodefinethenameoftheclass.
Toaddaclassstatement,enterthewordspublicclassandthentheclass'sname.
Addopeningandclosingcurlybracketstocontainthecontentsoftheclass(themethodandpropertydefinitions).
Forexample:publicclassMyClass{}Thewordpublicindicatesthattheclasscanbeaccessedfromanyothercode.
Forotheralternatives,seeAccesscontrolnamespaceattributes.
3Typeapackagestatementtoindicatethenameofthepackagethatcontainsyourclass.
Thesyntaxisthewordpackage,followedbythefullpackagename,followedbyopeningandclosingcurlybracketsaroundtheclassstatementblock)Forexample,changethecodeintheprevioussteptothefollowing:packagemypackage{publicclassMyClass{}}4Defineeachpropertyintheclassusingthevarstatementwithintheclassbody.
Thesyntaxisthesameasyouusetodeclareanyvariable(withtheadditionofthepublicmodifier).
Forexample,addingtheselinesbetweentheopeningandclosingcurlybracketsoftheclassdefinitioncreatespropertiesnamedtextProperty,numericProperty,anddateProperty:publicvartextProperty:String="somedefaultvalue";publicvarnumericProperty:Number=17;publicvardateProperty:Date;5Defineeachmethodintheclassusingthesamesyntaxthat'susedtodefineafunction.
Forexample:TocreateamyMethod()method,enter:publicfunctionmyMethod(param1:String,param2:Number):void{//dosomethingwithparameters}Tocreateaconstructor(thespecialmethodthatiscalledaspartoftheprocessofcreatinganinstanceofaclass),createamethodwhosenamematchesexactlythenameoftheclass:25LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011publicfunctionMyClass(){//dostufftosetinitialvaluesforproperties//andotherwisesetuptheobjecttextVariable="Hellothere!
";dateVariable=newDate(2001,5,11);}Ifyoudon'tincludeaconstructormethodinyourclass,thecompilerautomaticallycreatesanemptyconstructorinyourclass.
(Inotherwords,aconstructorwithnoparametersandnostatements.
)Thereareafewmoreclasselementsthatyoucandefine.
Theseelementsaremorecomplex.
Accessorsareaspecialcrossbetweenamethodandaproperty.
Whenyouwritethecodetodefinetheclass,youwritetheaccessorlikeamethod.
Youcanperformmultipleactionsratherthanjustreadingorassigningavalue,whichisallyoucandowhenyoudefineaproperty.
However,whenyoucreateaninstanceofyourclass,youtreattheaccessorlikeapropertyandusethenametoreadorassignthevalue.
EventsinActionScriptaren'tdefinedusingaspecificsyntax.
Instead,youdefineeventsinyourclassusingthefunctionalityoftheEventDispatcherclass.
MoreHelptopicsHandlingeventsExample:CreatingabasicapplicationActionScript3.
0canbeusedwithinanumberofapplicationdevelopmentenvironments,includingtheFlashProfessionalandFlashBuildertoolsoranytexteditor.
ThisexamplewalksthroughthestepsincreatingandenhancingasimpleActionScript3.
0applicationusingFlashProfessionalorFlashBuilder.
Theapplicationyou'llbuildpresentsasimplepatternforusingexternalActionScript3.
0classfilesinFlashProfessionalandFlex.
DesigningyourActionScriptapplicationThisexampleActionScriptapplicationisastandard"HelloWorld"application,soitsdesignissimple:TheapplicationiscalledHelloWorld.
Itdisplaysasingletextfieldcontainingthewords"HelloWorld!
"Theapplicationusesasingleobject-orientedclassnamedGreeter.
ThisdesignallowstheclasstobeusedfromwithinaFlashProfessionalorFlexproject.
Inthisexample,youfirstcreateabasicversionoftheapplication.
Nextyouaddfunctionalitytohavetheuserenterausernameandhavetheapplicationcheckthenameagainstalistofknownusers.
Withthatconcisedefinitioninplace,youcanstartbuildingtheapplicationitself.
CreatingtheHelloWorldprojectandtheGreeterclassThedesignstatementfortheHelloWorldapplicationsaysthatitscodeiseasytoreuse.
Toachievethatgoal,theapplicationusesasingleobject-orientedclassnamedGreeter.
YouusethatclassfromwithinanapplicationthatyoucreateinFlashBuilderorFlashProfessional.
26LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011TocreatetheHelloWorldprojectandGreeterclassinFlex:1InFlashBuilder,selectFile>New>FlexProject,2TypeHelloWorldastheProjectName.
MakesurethattheApplicationtypeissetto"Web(runsinAdobeFlashPlayer),"andthenclickFinish.
FlashBuildercreatesyourprojectanddisplaysitinthePackageExplorer.
BydefaulttheprojectalreadycontainsafilenamedHelloWorld.
mxml,andthatfileisopenintheeditor.
3NowtocreateacustomActionScriptclassfileinFlashBuilder,selectFile>New>ActionScriptClass.
4IntheNewActionScriptClassdialogbox,intheNamefield,typeGreeterastheclassname,andthenclickFinish.
AnewActionScripteditingwindowisdisplayed.
ContinuewithaddingcodetotheGreeterclass.
TocreatetheGreeterclassinFlashProfessional:1InFlashProfessional,selectFile>New.
2IntheNewDocumentdialogbox,selectActionScriptfile,andclickOK.
AnewActionScripteditingwindowisdisplayed.
3SelectFile>Save.
Selectafoldertocontainyourapplication,nametheActionScriptfileGreeter.
as,andthenclickOK.
ContinuewithaddingcodetotheGreeterclass.
AddingcodetotheGreeterclassTheGreeterclassdefinesanobject,Greeter,thatyouuseinyourHelloWorldapplication.
ToaddcodetotheGreeterclass:1Typethefollowingcodeintothenewfile(someofthecodemayhavebeenaddedforyou):package{publicclassGreeter{publicfunctionsayHello():String{vargreeting:String;greeting="HelloWorld!
";returngreeting;}}}TheGreeterclassincludesasinglesayHello()method,whichreturnsastringthatsays"HelloWorld!
".
2SelectFile>SavetosavethisActionScriptfile.
TheGreeterclassisnowreadytobeusedinanapplication.
CreatinganapplicationthatusesyourActionScriptcodeTheGreeterclassthatyouhavebuiltdefinesaself-containedsetofsoftwarefunctions,butitdoesnotrepresentacompleteapplication.
Tousetheclass,youcreateaFlashProfessionaldocumentorFlexproject.
ThecodeneedsaninstanceoftheGreeterclass.
Here'showtousetheGreeterclasstoyourapplication.
27LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011TocreateanActionScriptapplicationusingFlashProfessional:1SelectFile>New.
2IntheNewDocumentdialogbox,selectFlashFile(ActionScript3.
0),andclickOK.
Anewdocumentwindowisdisplayed.
3SelectFile>Save.
SelectthesamefolderthatcontainstheGreeter.
asclassfile,nametheFlashdocumentHelloWorld.
fla,andclickOK.
4IntheFlashProfessionaltoolspalette,selecttheTexttool.
DragacrosstheStagetodefineanewtextfieldapproximately300pixelswideand100pixelshigh.
5InthePropertiespanel,withthetextfieldstillselectedontheStage,setthetexttypeto"DynamicText.
"TypemainTextastheinstancenameofthetextfield.
6Clickthefirstframeofthemaintimeline.
OpentheActionspanelbychoosingWindow>Actions.
7IntheActionspanel,typethefollowingscript:varmyGreeter:Greeter=newGreeter();mainText.
text=myGreeter.
sayHello();8Savethefile.
ContinuewithPublishingandtestingyourActionScriptapplication.
TocreateanActionScriptapplicationusingFlashBuilder:1OpentheHelloWorld.
mxmlfile,andaddcodetomatchthefollowinglisting:ThisFlexprojectincludesfourMXMLtags:Antag,whichdefinestheApplicationcontainer28LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011Antag,whichdefinesthelayoutstyle(verticallayout)fortheApplicationtagAntagthatincludessomeActionScriptcodeAntag,whichdefinesafieldtodisplaytextmessagestotheuserThecodeinthetagdefinesaninitApp()methodthatiscalledwhentheapplicationloads.
TheinitApp()methodsetsthetextvalueofthemainTxtTextAreatothe"HelloWorld!
"stringreturnedbythesayHello()methodofthecustomclassGreeter,whichyoujustwrote.
2SelectFile>Savetosavetheapplication.
ContinuewithPublishingandtestingyourActionScriptapplication.
PublishingandtestingyourActionScriptapplicationSoftwaredevelopmentisaniterativeprocess.
Youwritesomecode,trytocompileit,andeditthecodeuntilitcompilescleanly.
Yourunthecompiledapplicationandtestittoseeifitfulfillstheintendeddesign.
Ifitdoesn't,youeditthecodeagainuntilitdoes.
TheFlashProfessionalandFlashBuilderdevelopmentenvironmentsofferanumberofwaystopublish,test,anddebugyourapplications.
HerearethebasicstepsfortestingtheHelloWorldapplicationineachenvironment.
TopublishandtestanActionScriptapplicationusingFlashProfessional:1Publishyourapplicationandwatchforcompilationerrors.
InFlashProfessional,selectControl>TestMovietocompileyourActionScriptcodeandruntheHelloWorldapplication.
2IfanyerrorsorwarningsaredisplayedintheOutputwindowwhenyoutestyourapplication,fixtheseerrorsintheHelloWorld.
flaorHelloWorld.
asfiles.
Thentrytestingtheapplicationagain.
3Iftherearenocompilationerrors,youseeaFlashPlayerwindowshowingtheHelloWorldapplication.
Youhavecreatedasimplebutcompleteobject-orientedapplicationthatusesActionScript3.
0.
ContinuewithEnhancingtheHelloWorldapplication.
TopublishandtestanActionScriptapplicationusingFlashBuilder:1SelectRun>RunHelloWorld.
2TheHelloWorldapplicationstarts.
IfanyerrorsorwarningsaredisplayedintheOutputwindowwhenyoutestyourapplication,fixtheerrorsintheHelloWorld.
mxmlorGreeter.
asfiles.
Thentrytestingtheapplicationagain.
Iftherearenocompilationerrors,abrowserwindowopensshowingtheHelloWorldapplication.
Thetext"HelloWorld!
"appears.
Youhavecreatedasimplebutcompleteobject-orientedapplicationthatusesActionScript3.
0.
ContinuewithEnhancingtheHelloWorldapplication.
EnhancingtheHelloWorldapplicationTomaketheapplicationalittlemoreinteresting,you'llnowmakeitaskforandvalidateausernameagainstapredefinedlistofnames.
FirstyouupdatetheGreeterclasstoaddnewfunctionality.
Thenyouupdatetheapplicationtousethenewfunctionality.
29LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011ToupdatetheGreeter.
asfile:1OpentheGreeter.
asfile.
2Changethecontentsofthefiletothefollowing(newandchangedlinesareshowninboldface):package{publicclassGreeter{/***Definesthenamesthatreceiveapropergreeting.
*/publicstaticvarvalidNames:Array=["Sammy","Frank","Dean"];/***Buildsagreetingstringusingthegivenname.
*/publicfunctionsayHello(userName:String=""):String{vargreeting:String;if(userName==""){greeting="Hello.
Pleasetypeyourusername,andthenpress"+"theEnterkey.
";}elseif(validName(userName)){greeting="Hello,"+userName+".
";}else{greeting="Sorry"+userName+",youarenotonthelist.
";}returngreeting;}/***CheckswhetheranameisinthevalidNameslist.
*/publicstaticfunctionvalidName(inputName:String=""):Boolean{if(validNames.
indexOf(inputName)>-1){returntrue;}else{returnfalse;}}}}TheGreeterclassnowhasanumberofnewfeatures:ThevalidNamesarraylistsvalidusernames.
ThearrayisinitializedtoalistofthreenameswhentheGreeterclassisloaded.
30LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011ThesayHello()methodnowacceptsausernameandchangesthegreetingbasedonsomeconditions.
IftheuserNameisanemptystring(""),thegreetingpropertyissettoprompttheuserforaname.
Iftheusernameisvalid,thegreetingbecomes"Hello,userName.
"Finally,ifeitherofthosetwoconditionsarenotmet,thegreetingvariableissetto"SorryuserName,youarenotonthelist.
"ThevalidName()methodreturnstrueiftheinputNameisfoundinthevalidNamesarray,andfalseifitisnotfound.
ThestatementvalidNames.
indexOf(inputName)checkseachofthestringsinthevalidNamesarrayagainsttheinputNamestring.
TheArray.
indexOf()methodreturnstheindexpositionofthefirstinstanceofanobjectinanarray.
Itreturnsthevalue-1iftheobjectisnotfoundinthearray.
NextyouedittheapplicationfilethatreferencesthisActionScriptclass.
TomodifytheapplicationusingFlashProfessional:1OpentheHelloWorld.
flafile.
2ModifythescriptinFrame1sothatanemptystring("")ispassedtotheGreeterclass'ssayHello()method:varmyGreeter:Greeter=newGreeter();mainText.
text=myGreeter.
sayHello("");3SelecttheTexttoolinthetoolspalette.
CreatetwonewtextfieldsontheStage.
PlacethemsidebysidedirectlyundertheexistingmainTexttextfield.
4Inthefirstnewtextfield,whichisthelabel,typethetextUserName:.
5Selecttheothernewtextfield,andinthePropertyinspector,selectInputTextasthetypeoftextfield.
SelectSinglelineastheLinetype.
TypetextInastheinstancename.
6Clickthefirstframeofthemaintimeline.
7IntheActionspanel,addthefollowinglinestotheendoftheexistingscript:mainText.
border=true;textIn.
border=true;textIn.
addEventListener(KeyboardEvent.
KEY_DOWN,keyPressed);functionkeyPressed(event:KeyboardEvent):void{if(event.
keyCode==Keyboard.
ENTER){mainText.
text=myGreeter.
sayHello(textIn.
text);}}Thenewcodeaddsthefollowingfunctionality:Thefirsttwolinessimplydefinebordersfortwotextfields.
Aninputtextfield,suchasthetextInfield,hasasetofeventsthatitcandispatch.
TheaddEventListener()methodletsyoudefineafunctionthatrunswhenatypeofeventoccurs.
Inthiscase,thateventisthepressingofakeyonthekeyboard.
ThekeyPressed()customfunctionchecksifthekeythatwaspressedistheEnterkey.
IfsoitcallsthesayHello()methodofthemyGreeterobject,passingthetextfromthetextIntextfieldasaparameter.
Thatmethodreturnsastringgreetingbasedonthevaluepassedin.
ThereturnedstringisthenassignedtothetextpropertyofthemainTexttextfield.
ThecompletescriptforFrame1isthefollowing:31LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/2011varmyGreeter:Greeter=newGreeter();mainText.
text=myGreeter.
sayHello("");mainText.
border=true;textIn.
border=true;textIn.
addEventListener(KeyboardEvent.
KEY_DOWN,keyPressed);functionkeyPressed(event:KeyboardEvent):void{if(event.
keyCode==Keyboard.
ENTER){mainText.
text=myGreeter.
sayHello(textIn.
text);}}8Savethefile.
9SelectControl>TestMovietoruntheapplication.
Whenyouruntheapplication,itpromptsyoutoenterausername.
Ifitisvalid(Sammy,Frank,orDean),theapplicationdisplaysthe"hello"confirmationmessage.
TomodifytheapplicationusingFlashBuilder:1OpentheHelloWorld.
mxmlfile.
2Nextmodifythetagtoindicatetotheuserthatitisfordisplayonly.
Changethebackgroundcolortoalightgrayandsettheeditableattributetofalse:3Nowaddthefollowinglinesrightaftertheclosingtag.
TheselinescreateaTextInputcomponentthatletstheuserenterausernamevalue:TheenterattributedefineswhathappenswhentheuserpressestheEnterkeyintheuserNameTxtfield.
Inthisexample,thecodepassesthetextinthefieldtotheGreeter.
sayHello()method.
ThegreetinginthemainTxtfieldchangesaccordingly.
TheHelloWorld.
mxmlfilelookslikethefollowing:32LEARNINGACTIONSCRIPT3.
0GettingstartedwithActionScriptLastupdated5/2/20114SavetheeditedHelloWorld.
mxmlfile.
SelectRun>RunHelloWorldtoruntheapplication.
Whenyouruntheapplication,theapplicationpromptsyoutoenterausername.
Ifitisvalid(Sammy,Frank,orDean),theapplicationdisplaysthe"Hello,userName"confirmationmessage.
33Lastupdated5/2/2011Chapter3:ActionScriptlanguageandsyntaxActionScript3.
0includesboththecoreActionScriptlanguageandtheAdobeFlashPlatformApplicationProgrammingInterface(API).
ThecorelanguageisthepartofActionScriptthatdefinesthesyntaxofthelanguageaswellasthetop-leveldatatypes.
ActionScript3.
0providesprogrammaticaccesstotheAdobeFlashPlatformruntimes:AdobeFlashPlayerandAdobeAIR.
LanguageoverviewObjectslieattheheartoftheActionScript3.
0language—theyareitsfundamentalbuildingblocks.
Everyvariableyoudeclare,everyfunctionyouwrite,andeveryclassinstanceyoucreateisanobject.
YoucanthinkofanActionScript3.
0programasagroupofobjectsthatcarryouttasks,respondtoevents,andcommunicatewithoneanother.
Programmersfamiliarwithobject-orientedprogramming(OOP)inJavaorC++maythinkofobjectsasmodulesthatcontaintwokindsofmembers:datastoredinmembervariablesorproperties,andbehavioraccessiblethroughmethods.
ActionScript3.
0definesobjectsinasimilarbutslightlydifferentway.
InActionScript3.
0,objectsaresimplycollectionsofproperties.
Thesepropertiesarecontainersthatcanholdnotonlydata,butalsofunctionsorotherobjects.
Ifafunctionisattachedtoanobjectinthisway,itiscalledamethod.
WhiletheActionScript3.
0definitionmayseemalittleoddtoprogrammerswithaJavaorC++background,inpractice,definingobjecttypeswithActionScript3.
0classesisverysimilartothewayclassesaredefinedinJavaorC++.
ThedistinctionbetweenthetwodefinitionsofobjectisimportantwhendiscussingtheActionScriptobjectmodelandotheradvancedtopics,butinmostothersituationsthetermpropertiesmeansclassmembervariablesasopposedtomethods.
ActionScript3.
0ReferencefortheAdobeFlashPlatform,forexample,usesthetermpropertiestomeanvariablesorgetter-setterproperties.
Itusesthetermmethodstomeanfunctionsthatarepartofaclass.
OnesubtledifferencebetweenclassesinActionScriptandclassesinJavaorC++isthatinActionScript,classesarenotjustabstractentities.
ActionScriptclassesarerepresentedbyclassobjectsthatstoretheclass'spropertiesandmethods.
ThisallowsfortechniquesthatmayseemalientoJavaandC++programmers,suchasincludingstatementsorexecutablecodeatthetoplevelofaclassorpackage.
AnotherdifferencebetweenActionScriptclassesandJavaorC++classesisthateveryActionScriptclasshassomethingcalledaprototypeobject.
InpreviousversionsofActionScript,prototypeobjects,linkedtogetherintoprototypechains,servedcollectivelyasthefoundationoftheentireclassinheritancehierarchy.
InActionScript3.
0,however,prototypeobjectsplayonlyasmallroleintheinheritancesystem.
Theprototypeobjectcanstillbeuseful,however,asanalternativetostaticpropertiesandmethodsifyouwanttoshareapropertyanditsvalueamongalltheinstancesofaclass.
Inthepast,advancedActionScriptprogrammerscoulddirectlymanipulatetheprototypechainwithspecialbuilt-inlanguageelements.
Nowthatthelanguageprovidesamorematureimplementationofaclass-basedprogramminginterface,manyofthesespeciallanguageelements,suchas__proto__and__resolve,arenolongerpartofthelanguage.
Moreover,optimizationsoftheinternalinheritancemechanismthatprovidesignificantperformanceimprovementsprecludedirectaccesstotheinheritancemechanism.
34LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011ObjectsandclassesInActionScript3.
0,everyobjectisdefinedbyaclass.
Aclasscanbethoughtofasatemplateorablueprintforatypeofobject.
Classdefinitionscanincludevariablesandconstants,whichholddatavalues,andmethods,whicharefunctionsthatencapsulatebehaviorboundtotheclass.
Thevaluesstoredinpropertiescanbeprimitivevaluesorotherobjects.
Primitivevaluesarenumbers,strings,orBooleanvalues.
ActionScriptcontainsanumberofbuilt-inclassesthatarepartofthecorelanguage.
Someofthesebuilt-inclasses,suchasNumber,BooleanandString,representtheprimitivevaluesavailableinActionScript.
Others,suchastheArray,Math,andXMLclasses,definemorecomplexobjects.
Allclasses,whetherbuilt-inoruser-defined,derivefromtheObjectclass.
ForprogrammerswithpreviousActionScriptexperience,itisimportanttonotethattheObjectdatatypeisnolongerthedefaultdatatype,eventhoughallotherclassesstillderivefromit.
InActionScript2.
0,thefollowingtwolinesofcodewereequivalentbecausethelackofatypeannotationmeantthatavariablewouldbeoftypeObject:varsomeObj:Object;varsomeObj;ActionScript3.
0,however,introducestheconceptofuntypedvariables,whichcanbedesignatedinthefollowingtwoways:varsomeObj:*;varsomeObj;AnuntypedvariableisnotthesameasavariableoftypeObject.
Thekeydifferenceisthatuntypedvariablescanholdthespecialvalueundefined,whileavariableoftypeObjectcannotholdthatvalue.
Youcandefineyourownclassesusingtheclasskeyword.
Youcandeclareclasspropertiesinthreeways:constantscanbedefinedwiththeconstkeyword,variablesaredefinedwiththevarkeyword,andgetterandsetterpropertiesaredefinedbyusingthegetandsetattributesinamethoddeclaration.
Youcandeclaremethodswiththefunctionkeyword.
Youcreateaninstanceofaclassbyusingthenewoperator.
ThefollowingexamplecreatesaninstanceoftheDateclasscalledmyBirthday.
varmyBirthday:Date=newDate();PackagesandnamespacesPackagesandnamespacesarerelatedconcepts.
Packagesallowyoutobundleclassdefinitionstogetherinawaythatfacilitatescodesharingandminimizesnamingconflicts.
Namespacesallowyoutocontrolthevisibilityofidentifiers,suchaspropertyandmethodnames,andcanbeappliedtocodewhetheritresidesinsideoroutsideapackage.
Packagesletyouorganizeyourclassfiles,andnamespacesletyoumanagethevisibilityofindividualpropertiesandmethods.
PackagesPackagesinActionScript3.
0areimplementedwithnamespaces,butarenotsynonymouswiththem.
Whenyoudeclareapackage,youareimplicitlycreatingaspecialtypeofnamespacethatisguaranteedtobeknownatcompiletime.
Namespaces,whencreatedexplicitly,arenotnecessarilyknownatcompiletime.
Thefollowingexampleusesthepackagedirectivetocreateasimplepackagecontainingoneclass:35LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011packagesamples{publicclassSampleCode{publicvarsampleGreeting:String;publicfunctionsampleFunction(){trace(sampleGreeting+"fromsampleFunction()");}}}ThenameoftheclassinthisexampleisSampleCode.
Becausetheclassisinsidethesamplespackage,thecompilerautomaticallyqualifiestheclassnameatcompiletimeintoitsfullyqualifiedname:samples.
SampleCode.
Thecompileralsoqualifiesthenamesofanypropertiesormethods,sothatsampleGreetingandsampleFunction()becomesamples.
SampleCode.
sampleGreetingandsamples.
SampleCode.
sampleFunction(),respectively.
Manydevelopers,especiallythosewithJavaprogrammingbackgrounds,maychoosetoplaceonlyclassesatthetoplevelofapackage.
ActionScript3.
0,however,supportsnotonlyclassesatthetoplevelofapackage,butalsovariables,functions,andevenstatements.
Oneadvanceduseofthisfeatureistodefineanamespaceatthetoplevelofapackagesothatitisavailabletoallclassesinthatpackage.
Note,however,thatonlytwoaccessspecifiers,publicandinternal,areallowedatthetoplevelofapackage.
UnlikeJava,whichallowsyoutodeclarenestedclassesasprivate,ActionScript3.
0doesn'tsupportnestedorprivateclasses.
Inmanyotherways,however,ActionScript3.
0packagesaresimilartopackagesintheJavaprogramminglanguage.
Asyoucanseeinthepreviousexample,fullyqualifiedpackagereferencesareexpressedusingthedotoperator(.
),justastheyareinJava.
Youcanusepackagestoorganizeyourcodeintoanintuitivehierarchicalstructureforusebyotherprogrammers.
Thisfacilitatescodesharingbyallowingyoutocreateyourownpackagetosharewithothers,andtousepackagescreatedbyothersinyourcode.
Theuseofpackagesalsohelpstoensurethattheidentifiernamesthatyouuseareuniqueanddonotconflictwithotheridentifiernames.
Infact,somewouldarguethatthisistheprimarybenefitofpackages.
Forexample,twoprogrammerswhowanttosharetheircodewitheachothermayhaveeachcreatedaclasscalledSampleCode.
Withoutpackages,thiswouldcreateanameconflict,andtheonlyresolutionwouldbetorenameoneoftheclasses.
Withpackages,however,thenameconflictiseasilyavoidedbyplacingone,orpreferablyboth,oftheclassesinpackageswithuniquenames.
Youcanalsoincludeembeddeddotsinyourpackagenametocreatenestedpackages.
Thisallowsyoutocreateahierarchicalorganizationofpackages.
Agoodexampleofthisistheflash.
displaypackageprovidedbyActionScript3.
0.
Theflash.
displaypackageisnestedinsidetheflashpackage.
MostofActionScript3.
0isorganizedundertheflashpackage.
Forexample,theflash.
displaypackagecontainsthedisplaylistAPI,andtheflash.
eventspackagecontainstheneweventmodel.
CreatingpackagesActionScript3.
0providessignificantflexibilityinthewayyouorganizeyourpackages,classes,andsourcefiles.
PreviousversionsofActionScriptallowedonlyoneclasspersourcefileandrequiredthenameofthesourcefiletomatchthenameoftheclass.
ActionScript3.
0allowsyoutoincludemultipleclassesinonesourcefile,butonlyoneclassineachfilecanbemadeavailabletocodethatisexternaltothatfile.
Inotherwords,onlyoneclassineachfilecanbedeclaredinsideapackagedeclaration.
Youmustdeclareanyadditionalclassesoutsideyourpackagedefinition,whichmakesthoseclassesinvisibletocodeoutsidethatsourcefile.
Thenameoftheclassdeclaredinsidethepackagedefinitionmustmatchthenameofthesourcefile.
36LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011ActionScript3.
0alsoprovidesmoreflexibilityinthewayyoudeclarepackages.
InpreviousversionsofActionScript,packagesmerelyrepresenteddirectoriesinwhichyouplacedsourcefiles,andyoudidn'tdeclarepackageswiththepackagestatement,butratherincludedthepackagenameaspartofthefullyqualifiedclassnameinyourclassdeclaration.
AlthoughpackagesstillrepresentdirectoriesinActionScript3.
0,packagescancontainmorethanjustclasses.
InActionScript3.
0,youusethepackagestatementtodeclareapackage,whichmeansthatyoucanalsodeclarevariables,functions,andnamespacesatthetoplevelofapackage.
Youcanevenincludeexecutablestatementsatthetoplevelofapackage.
Ifyoudodeclarevariables,functions,ornamespacesatthetoplevelofapackage,theonlyattributesavailableatthatlevelarepublicandinternal,andonlyonepackage-leveldeclarationperfilecanusethepublicattribute,whetherthatdeclarationisaclass,variable,function,ornamespace.
Packagesareusefulfororganizingyourcodeandforpreventingnameconflicts.
Youshouldnotconfusetheconceptofpackageswiththeunrelatedconceptofclassinheritance.
Twoclassesthatresideinthesamepackagehaveanamespaceincommon,butarenotnecessarilyrelatedtoeachotherinanyotherway.
Likewise,anestedpackagemayhavenosemanticrelationshiptoitsparentpackage.
ImportingpackagesIfyouwanttouseaclassthatisinsideapackage,youmustimporteitherthepackageorthespecificclass.
ThisdiffersfromActionScript2.
0,whereimportingclasseswasoptional.
Forexample,considertheSampleCodeclassexamplepresentedpreviously.
Iftheclassresidesinapackagenamedsamples,youmustuseoneofthefollowingimportstatementsbeforeusingtheSampleCodeclass:importsamples.
*;orimportsamples.
SampleCode;Ingeneral,importstatementsshouldbeasspecificaspossible.
IfyouplantouseonlytheSampleCodeclassfromthesamplespackage,youshouldimportonlytheSampleCodeclassratherthantheentirepackagetowhichitbelongs.
Importingentirepackagesmayleadtounexpectednameconflicts.
Youmustalsoplacethesourcecodethatdefinesthepackageorclasswithinyourclasspath.
Theclasspathisauser-definedlistoflocaldirectorypathsthatdetermineswherethecompilersearchesforimportedpackagesandclasses.
Theclasspathissometimescalledthebuildpathorsourcepath.
Afteryouhaveproperlyimportedtheclassorpackage,youcanuseeitherthefullyqualifiednameoftheclass(samples.
SampleCode)ormerelytheclassnamebyitself(SampleCode).
Fullyqualifiednamesareusefulwhenidenticallynamedclasses,methods,orpropertiesresultinambiguouscode,butcanbedifficulttomanageifusedforallidentifiers.
Forexample,theuseofthefullyqualifiednameresultsinverbosecodewhenyouinstantiateaSampleCodeclassinstance:varmySample:samples.
SampleCode=newsamples.
SampleCode();Asthelevelsofnestedpackagesincrease,thereadabilityofyourcodedecreases.
Insituationswhereyouareconfidentthatambiguousidentifiersarenotaproblem,youcanmakeyourcodeeasiertoreadbyusingsimpleidentifiers.
Forexample,instantiatinganewinstanceoftheSampleCodeclassismuchlessverboseifyouuseonlytheclassidentifier:varmySample:SampleCode=newSampleCode();Ifyouattempttouseidentifiernameswithoutfirstimportingtheappropriatepackageorclass,thecompilercan'tfindtheclassdefinitions.
Ontheotherhand,ifyoudoimportapackageorclass,anyattempttodefineanamethatconflictswithanimportednamegeneratesanerror.
37LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Whenapackageiscreated,thedefaultaccessspecifierforallmembersofthatpackageisinternal,whichmeansthat,bydefault,packagemembersareonlyvisibletoothermembersofthatpackage.
Ifyouwantaclasstobeavailabletocodeoutsidethepackage,youmustdeclarethatclasstobepublic.
Forexample,thefollowingpackagecontainstwoclasses,SampleCodeandCodeFormatter://SampleCode.
asfilepackagesamples{publicclassSampleCode{}}//CodeFormatter.
asfilepackagesamples{classCodeFormatter{}}TheSampleCodeclassisvisibleoutsidethepackagebecauseitisdeclaredasapublicclass.
TheCodeFormatterclass,however,isvisibleonlywithinthesamplespackageitself.
IfyouattempttoaccesstheCodeFormatterclassoutsidethesamplespackage,itgeneratesanerror,asthefollowingexampleshows:importsamples.
SampleCode;importsamples.
CodeFormatter;varmySample:SampleCode=newSampleCode();//okay,publicclassvarmyFormatter:CodeFormatter=newCodeFormatter();//errorIfyouwantbothclassestobeavailableoutsidethepackage,youmustdeclarebothclassestobepublic.
Youcannotapplythepublicattributetothepackagedeclaration.
Fullyqualifiednamesareusefulforresolvingnameconflictsthatmayoccurwhenusingpackages.
Suchascenariomayariseifyouimporttwopackagesthatdefineclasseswiththesameidentifier.
Forexample,considerthefollowingpackage,whichalsohasaclassnamedSampleCode:packagelangref.
samples{publicclassSampleCode{}}Ifyouimportbothclasses,asfollows,youhaveanameconflictwhenusingtheSampleCodeclass:importsamples.
SampleCode;importlangref.
samples.
SampleCode;varmySample:SampleCode=newSampleCode();//nameconflictThecompilerhasnowayofknowingwhichSampleCodeclasstouse.
Toresolvethisconflict,youmustusethefullyqualifiednameofeachclass,asfollows:varsample1:samples.
SampleCode=newsamples.
SampleCode();varsample2:langref.
samples.
SampleCode=newlangref.
samples.
SampleCode();Note:ProgrammerswithaC++backgroundoftenconfusetheimportstatementwith#include.
The#includedirectiveisnecessaryinC++becauseC++compilersprocessonefileatatime,anddon'tlookinotherfilesforclassdefinitionsunlessaheaderfileisexplicitlyincluded.
ActionScript3.
0hasanincludedirective,butitisnotdesignedtoimportclassesandpackages.
ToimportclassesorpackagesinActionScript3.
0,youmustusetheimportstatementandplacethesourcefilethatcontainsthepackageintheclasspath.
38LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011NamespacesNamespacesgiveyoucontroloverthevisibilityofthepropertiesandmethodsthatyoucreate.
Thinkofthepublic,private,protected,andinternalaccesscontrolspecifiersasbuilt-innamespaces.
Ifthesepredefinedaccesscontrolspecifiersdonotsuityourneeds,youcancreateyourownnamespaces.
IfyouarefamiliarwithXMLnamespaces,muchofthisdiscussionwillnotbenewtoyou,althoughthesyntaxanddetailsoftheActionScriptimplementationareslightlydifferentfromthoseofXML.
Ifyouhaveneverworkedwithnamespacesbefore,theconceptitselfisstraightforward,buttheimplementationhasspecificterminologythatyouwillneedtolearn.
Tounderstandhownamespaceswork,ithelpstoknowthatthenameofapropertyormethodalwayscontainstwoparts:anidentifierandanamespace.
Theidentifieriswhatyougenerallythinkofasaname.
Forexample,theidentifiersinthefollowingclassdefinitionaresampleGreetingandsampleFunction():classSampleCode{varsampleGreeting:String;functionsampleFunction(){trace(sampleGreeting+"fromsampleFunction()");}}Wheneverdefinitionsarenotprecededbyanamespaceattribute,theirnamesarequalifiedbythedefaultinternalnamespace,whichmeanstheyarevisibleonlytocallersinthesamepackage.
Ifthecompilerissettostrictmode,thecompilerissuesawarningthattheinternalnamespaceappliestoanyidentifierwithoutanamespaceattribute.
Toensurethatanidentifierisavailableeverywhere,youmustspecificallyprecedetheidentifiernamewiththepublicattribute.
Inthepreviousexamplecode,bothsampleGreetingandsampleFunction()haveanamespacevalueofinternal.
Therearethreebasicstepstofollowwhenusingnamespaces.
First,youmustdefinethenamespaceusingthenamespacekeyword.
Forexample,thefollowingcodedefinestheversion1namespace:namespaceversion1;Second,youapplyyournamespacebyusingitinsteadofanaccesscontrolspecifierinapropertyormethoddeclaration.
ThefollowingexampleplacesafunctionnamedmyFunction()intotheversion1namespace:version1functionmyFunction(){}Third,onceyou'veappliedthenamespace,youcanreferenceitwiththeusedirectiveorbyqualifyingthenameofanidentifierwithanamespace.
ThefollowingexamplereferencesthemyFunction()functionthroughtheusedirective:usenamespaceversion1;myFunction();YoucanalsouseaqualifiednametoreferencethemyFunction()function,asthefollowingexampleshows:version1::myFunction();DefiningnamespacesNamespacescontainonevalue,theUniformResourceIdentifier(URI),whichissometimescalledthenamespacename.
AURIallowsyoutoensurethatyournamespacedefinitionisunique.
Youcreateanamespacebydeclaringanamespacedefinitioninoneoftwoways.
YoucaneitherdefineanamespacewithanexplicitURI,asyouwoulddefineanXMLnamespace,oryoucanomittheURI.
ThefollowingexampleshowshowanamespacecanbedefinedusingaURI:namespaceflash_proxy="http://www.
adobe.
com/flash/proxy";39LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011TheURIservesasauniqueidentificationstringforthatnamespace.
IfyouomittheURI,asinthefollowingexample,thecompilercreatesauniqueinternalidentificationstringinplaceoftheURI.
Youdonothaveaccesstothisinternalidentificationstring.
namespaceflash_proxy;Onceyoudefineanamespace,withorwithoutaURI,thatnamespacecannotberedefinedinthesamescope.
Anattempttodefineanamespacethathasbeendefinedearlierinthesamescoperesultsinacompilererror.
Ifanamespaceisdefinedwithinapackageoraclass,thenamespacemaynotbevisibletocodeoutsidethatpackageorclassunlesstheappropriateaccesscontrolspecifierisused.
Forexample,thefollowingcodeshowstheflash_proxynamespacedefinedwithintheflash.
utilspackage.
Inthefollowingexample,thelackofanaccesscontrolspecifiermeansthattheflash_proxynamespacewouldbevisibleonlytocodewithintheflash.
utilspackageandwouldnotbevisibletoanycodeoutsidethepackage:packageflash.
utils{namespaceflash_proxy;}Thefollowingcodeusesthepublicattributetomaketheflash_proxynamespacevisibletocodeoutsidethepackage:packageflash.
utils{publicnamespaceflash_proxy;}ApplyingnamespacesApplyinganamespacemeansplacingadefinitionintoanamespace.
Definitionsthatcanbeplacedintonamespacesincludefunctions,variables,andconstants(youcannotplaceaclassintoacustomnamespace).
Consider,forexample,afunctiondeclaredusingthepublicaccesscontrolnamespace.
Usingthepublicattributeinafunctiondefinitionplacesthefunctionintothepublicnamespace,whichmakesthefunctionavailabletoallcode.
Onceyouhavedefinedanamespace,youcanusethenamespacethatyoudefinedthesamewayyouwouldusethepublicattribute,andthedefinitionisavailabletocodethatcanreferenceyourcustomnamespace.
Forexample,ifyoudefineanamespaceexample1,youcanaddamethodcalledmyFunction()usingexample1asanattribute,asthefollowingexampleshows:namespaceexample1;classsomeClass{example1myFunction(){}}DeclaringthemyFunction()methodusingthenamespaceexample1asanattributemeansthatthemethodbelongstotheexample1namespace.
Youshouldbearinmindthefollowingwhenapplyingnamespaces:Youcanapplyonlyonenamespacetoeachdeclaration.
Thereisnowaytoapplyanamespaceattributetomorethanonedefinitionatatime.
Inotherwords,ifyouwanttoapplyyournamespacetotendifferentfunctions,youmustaddyournamespaceasanattributetoeachofthetenfunctiondefinitions.
Ifyouapplyanamespace,youcannotalsospecifyanaccesscontrolspecifierbecausenamespacesandaccesscontrolspecifiersaremutuallyexclusive.
Inotherwords,youcannotdeclareafunctionorpropertyaspublic,private,protected,orinternalinadditiontoapplyingyournamespace.
40LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011ReferencingnamespacesThereisnoneedtoexplicitlyreferenceanamespacewhenyouuseamethodorpropertydeclaredwithanyoftheaccesscontrolnamespaces,suchaspublic,private,protected,andinternal.
Thisisbecauseaccesstothesespecialnamespacesiscontrolledbycontext.
Forexample,definitionsplacedintotheprivatenamespaceareautomaticallyavailabletocodewithinthesameclass.
Fornamespacesthatyoudefine,however,suchcontextsensitivitydoesnotexist.
Touseamethodorpropertythatyouhaveplacedintoacustomnamespace,youmustreferencethenamespace.
Youcanreferencenamespaceswiththeusenamespacedirectiveoryoucanqualifythenamewiththenamespaceusingthenamequalifier(::)punctuator.
Referencinganamespacewiththeusenamespacedirective"opens"thenamespace,sothatitcanapplytoanyidentifiersthatarenotqualified.
Forexample,ifyouhavedefinedtheexample1namespace,youcanaccessnamesinthatnamespacebyusingusenamespaceexample1:usenamespaceexample1;myFunction();Youcanopenmorethanonenamespaceatatime.
Onceyouopenanamespacewithusenamespace,itremainsopenthroughouttheblockofcodeinwhichitwasopened.
Thereisnowaytoexplicitlycloseanamespace.
Havingmorethanoneopennamespace,however,increasesthelikelihoodofnameconflicts.
Ifyouprefernottoopenanamespace,youcanavoidtheusenamespacedirectivebyqualifyingthemethodorpropertynamewiththenamespaceandthenamequalifierpunctuator.
Forexample,thefollowingcodeshowshowyoucanqualifythenamemyFunction()withtheexample1namespace:example1::myFunction();UsingnamespacesYoucanfindareal-worldexampleofanamespacethatisusedtopreventnameconflictsintheflash.
utils.
ProxyclassthatispartofActionScript3.
0.
TheProxyclass,whichisthereplacementfortheObject.
__resolvepropertyfromActionScript2.
0,allowsyoutointerceptreferencestoundefinedpropertiesormethodsbeforeanerroroccurs.
AllofthemethodsoftheProxyclassresideintheflash_proxynamespacetopreventnameconflicts.
Tobetterunderstandhowtheflash_proxynamespaceisused,youneedtounderstandhowtousetheProxyclass.
ThefunctionalityoftheProxyclassisavailableonlytoclassesthatinheritfromit.
Inotherwords,ifyouwanttousethemethodsoftheProxyclassonanobject,theobject'sclassdefinitionmustextendtheProxyclass.
Forexample,ifyouwanttointerceptattemptstocallanundefinedmethod,youwouldextendtheProxyclassandthenoverridethecallProperty()methodoftheProxyclass.
Youmayrecallthatimplementingnamespacesisusuallyathree-stepprocessofdefining,applying,andthenreferencinganamespace.
BecauseyouneverexplicitlycallanyoftheProxyclassmethods,however,theflash_proxynamespaceisonlydefinedandapplied,butneverreferenced.
ActionScript3.
0definestheflash_proxynamespaceandappliesitintheProxyclass.
Yourcodeonlyneedstoapplytheflash_proxynamespacetoclassesthatextendtheProxyclass.
Theflash_proxynamespaceisdefinedintheflash.
utilspackageinamannersimilartothefollowing:packageflash.
utils{publicnamespaceflash_proxy;}ThenamespaceisappliedtothemethodsoftheProxyclassasshowninthefollowingexcerptfromtheProxyclass:41LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011publicclassProxy{flash_proxyfunctioncallProperty(name:*,.
.
.
rest):*flash_proxyfunctiondeleteProperty(name:*):Boolean.
.
.
}Asthefollowingcodeshows,youmustfirstimportboththeProxyclassandtheflash_proxynamespace.
YoumustthendeclareyourclasssuchthatitextendstheProxyclass(youmustalsoaddthedynamicattributeifyouarecompilinginstrictmode).
WhenyouoverridethecallProperty()method,youmustusetheflash_proxynamespace.
package{importflash.
utils.
Proxy;importflash.
utils.
flash_proxy;dynamicclassMyProxyextendsProxy{flash_proxyoverridefunctioncallProperty(name:*,.
.
.
rest):*{trace("methodcallintercepted:"+name);}}}IfyoucreateaninstanceoftheMyProxyclassandcallanundefinedmethod,suchasthetesting()methodcalledinthefollowingexample,yourProxyobjectinterceptsthemethodcallandexecutesthestatementsinsidetheoverriddencallProperty()method(inthiscase,asimpletrace()statement).
varmySample:MyProxy=newMyProxy();mySample.
testing();//methodcallintercepted:testingTherearetwoadvantagestohavingthemethodsoftheProxyclassinsidetheflash_proxynamespace.
First,havingaseparatenamespacereducesclutterinthepublicinterfaceofanyclassthatextendstheProxyclass.
(ThereareaboutadozenmethodsintheProxyclassthatyoucanoverride,allofwhicharenotdesignedtobecalleddirectly.
Placingalloftheminthepublicnamespacecouldbeconfusing.
)Second,useoftheflash_proxynamespaceavoidsnameconflictsincaseyourProxysubclasscontainsinstancemethodswithnamesthatmatchanyoftheProxyclassmethods.
Forexample,youmaywanttonameoneofyourownmethodscallProperty().
Thefollowingcodeisacceptable,becauseyourversionofthecallProperty()methodisinadifferentnamespace:dynamicclassMyProxyextendsProxy{publicfunctioncallProperty(){}flash_proxyoverridefunctioncallProperty(name:*,.
.
.
rest):*{trace("methodcallintercepted:"+name);}}Namespacescanalsobehelpfulwhenyouwanttoprovideaccesstomethodsorpropertiesinawaythatcannotbeaccomplishedwiththefouraccesscontrolspecifiers(public,private,internal,andprotected).
Forexample,youmayhaveafewutilitymethodsthatarespreadoutacrossseveralpackages.
Youwantthesemethodsavailabletoallofyourpackages,butyoudon'twantthemethodstobepublic.
Toaccomplishthis,youcancreateanamespaceanduseitasyourownspecialaccesscontrolspecifier.
42LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Thefollowingexampleusesauser-definednamespacetogrouptwofunctionsthatresideindifferentpackages.
Bygroupingthemintothesamenamespace,youcanmakebothfunctionsvisibletoaclassorpackagethroughasingleusenamespacestatement.
Thisexampleusesfourfilestodemonstratethetechnique.
Allofthefilesmustbewithinyourclasspath.
Thefirstfile,myInternal.
as,isusedtodefinethemyInternalnamespace.
Becausethefileisinapackagenamedexample,youmustplacethefileintoafoldernamedexample.
Thenamespaceismarkedaspublicsothatitcanbeimportedintootherpackages.
//myInternal.
asinfolderexamplepackageexample{publicnamespacemyInternal="http://www.
adobe.
com/2006/actionscript/examples";}Thesecondandthirdfiles,Utility.
asandHelper.
as,definetheclassesthatcontainmethodsthatshouldbeavailabletootherpackages.
TheUtilityclassisintheexample.
alphapackage,whichmeansthatthefileshouldbeplacedinsideafoldernamedalphathatisasubfolderoftheexamplefolder.
TheHelperclassisintheexample.
betapackage,whichmeansthatthefileshouldbeplacedinsideafoldernamedbetathatisalsoasubfolderoftheexamplefolder.
Bothofthesepackages,example.
alphaandexample.
beta,mustimportthenamespacebeforeusingit.
//Utility.
asintheexample/alphafolderpackageexample.
alpha{importexample.
myInternal;publicclassUtility{privatestaticvar_taskCounter:int=0;publicstaticfunctionsomeTask(){_taskCounter++;}myInternalstaticfunctiongettaskCounter():int{return_taskCounter;}}}43LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011//Helper.
asintheexample/betafolderpackageexample.
beta{importexample.
myInternal;publicclassHelper{privatestaticvar_timeStamp:Date;publicstaticfunctionsomeTask(){_timeStamp=newDate();}myInternalstaticfunctiongetlastCalled():Date{return_timeStamp;}}}Thefourthfile,NamespaceUseCase.
as,isthemainapplicationclass,andshouldbeasiblingtotheexamplefolder.
InFlashProfessional,thisclasswouldbeusedasthedocumentclassfortheFLA.
TheNamespaceUseCaseclassalsoimportsthemyInternalnamespaceandusesittocallthetwostaticmethodsthatresideintheotherpackages.
Theexampleusesstaticmethodsonlytosimplifythecode.
BothstaticandinstancemethodscanbeplacedinthemyInternalnamespace.
//NamespaceUseCase.
aspackage{importflash.
display.
MovieClip;importexample.
myInternal;//importnamespaceimportexample.
alpha.
Utility;//importUtilityclassimportexample.
beta.
Helper;//importHelperclasspublicclassNamespaceUseCaseextendsMovieClip{publicfunctionNamespaceUseCase(){usenamespacemyInternal;Utility.
someTask();Utility.
someTask();trace(Utility.
taskCounter);//2Helper.
someTask();trace(Helper.
lastCalled);//[timesomeTask()waslastcalled]}}}44LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011VariablesVariablesallowyoutostorevaluesthatyouuseinyourprogram.
Todeclareavariable,youmustusethevarstatementwiththevariablename.
InActionScript3.
0,useofthevarstatementisalwaysrequired.
Forexample,thefollowinglineofActionScriptdeclaresavariablenamedi:vari;Ifyouomitthevarstatementwhendeclaringavariable,yougetacompilererrorinstrictmodeandrun-timeerrorinstandardmode.
Forexample,thefollowinglineofcoderesultsinanerrorifthevariableihasnotbeenpreviouslydefined:i;//errorifiwasnotpreviouslydefinedToassociateavariablewithadatatype,youmustdosowhenyoudeclarethevariable.
Declaringavariablewithoutdesignatingthevariable'stypeislegal,butgeneratesacompilerwarninginstrictmode.
Youdesignateavariable'stypebyappendingthevariablenamewithacolon(:),followedbythevariable'stype.
Forexample,thefollowingcodedeclaresavariableithatisoftypeint:vari:int;Youcanassignavaluetoavariableusingtheassignmentoperator(=).
Forexample,thefollowingcodedeclaresavariableiandassignsthevalue20toit:vari:int;i=20;Youmayfinditmoreconvenienttoassignavaluetoavariableatthesametimethatyoudeclarethevariable,asinthefollowingexample:vari:int=20;Thetechniqueofassigningavaluetoavariableatthetimeitisdeclarediscommonlyusednotonlywhenassigningprimitivevaluessuchasintegersandstrings,butalsowhencreatinganarrayorinstantiatinganinstanceofaclass.
Thefollowingexampleshowsanarraythatisdeclaredandassignedavalueusingonelineofcode.
varnumArray:Array=["zero","one","two"];Youcancreateaninstanceofaclassbyusingthenewoperator.
ThefollowingexamplecreatesaninstanceofanamedCustomClass,andassignsareferencetothenewlycreatedclassinstancetothevariablenamedcustomItem:varcustomItem:CustomClass=newCustomClass();Ifyouhavemorethanonevariabletodeclare,youcandeclarethemallononelineofcodebyusingthecommaoperator(,)toseparatethevariables.
Forexample,thefollowingcodedeclaresthreevariablesononelineofcode:vara:int,b:int,c:int;Youcanalsoassignvaluestoeachofthevariablesonthesamelineofcode.
Forexample,thefollowingcodedeclaresthreevariables(a,b,andc)andassignseachavalue:vara:int=10,b:int=20,c:int=30;Althoughyoucanusethecommaoperatortogroupvariabledeclarationsintoonestatement,doingsomayreducethereadabilityofyourcode.
45LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011UnderstandingvariablescopeThescopeofavariableistheareaofyourcodewherethevariablecanbeaccessedbyalexicalreference.
Aglobalvariableisonethatisdefinedinallareasofyourcode,whereasalocalvariableisonethatisdefinedinonlyonepartofyourcode.
InActionScript3.
0,variablesarealwaysassignedthescopeofthefunctionorclassinwhichtheyaredeclared.
Aglobalvariableisavariablethatyoudefineoutsideofanyfunctionorclassdefinition.
Forexample,thefollowingcodecreatesaglobalvariablestrGlobalbydeclaringitoutsideofanyfunction.
Theexampleshowsthataglobalvariableisavailablebothinsideandoutsidethefunctiondefinition.
varstrGlobal:String="Global";functionscopeTest(){trace(strGlobal);//Global}scopeTest();trace(strGlobal);//GlobalYoudeclarealocalvariablebydeclaringthevariableinsideafunctiondefinition.
Thesmallestareaofcodeforwhichyoucandefinealocalvariableisafunctiondefinition.
Alocalvariabledeclaredwithinafunctionexistsonlyinthatfunction.
Forexample,ifyoudeclareavariablenamedstr2withinafunctionnamedlocalScope(),thatvariableisnotavailableoutsidethefunction.
functionlocalScope(){varstrLocal:String="local";}localScope();trace(strLocal);//errorbecausestrLocalisnotdefinedgloballyIfthevariablenameyouuseforyourlocalvariableisalreadydeclaredasaglobalvariable,thelocaldefinitionhides(orshadows)theglobaldefinitionwhilethelocalvariableisinscope.
Theglobalvariablestillexistsoutsideofthefunction.
Forexample,thefollowingcodecreatesaglobalstringvariablenamedstr1,andthencreatesalocalvariableofthesamenameinsidethescopeTest()function.
Thetracestatementinsidethefunctionoutputsthelocalvalueofthevariable,butthetracestatementoutsidethefunctionoutputstheglobalvalueofthevariable.
varstr1:String="Global";functionscopeTest(){varstr1:String="Local";trace(str1);//Local}scopeTest();trace(str1);//GlobalActionScriptvariables,unlikevariablesinC++andJava,donothaveblock-levelscope.
Ablockofcodeisanygroupofstatementsbetweenanopeningcurlybracket({)andaclosingcurlybracket(}).
Insomeprogramminglanguages,suchasC++andJava,variablesdeclaredinsideablockofcodearenotavailableoutsidethatblockofcode.
Thisrestrictionofscopeiscalledblock-levelscope,anddoesnotexistinActionScript.
Ifyoudeclareavariableinsideablockofcode,thatvariableisavailablenotonlyinthatblockofcode,butalsoinanyotherpartsofthefunctiontowhichthecodeblockbelongs.
Forexample,thefollowingfunctioncontainsvariablesthataredefinedinvariousblockscopes.
Allthevariablesareavailablethroughoutthefunction.
46LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011functionblockTest(testArray:Array){varnumElements:int=testArray.
length;if(numElements>0){varelemStr:String="Element#";for(vari:int=0;i0}blockTest(["Earth","Moon","Sun"]);Aninterestingimplicationofthelackofblock-levelscopeisthatyoucanreadorwritetoavariablebeforeitisdeclared,aslongasitisdeclaredbeforethefunctionends.
Thisisbecauseofatechniquecalledhoisting,whichmeansthatthecompilermovesallvariabledeclarationstothetopofthefunction.
Forexample,thefollowingcodecompileseventhoughtheinitialtrace()functionforthenumvariablehappensbeforethenumvariableisdeclared:trace(num);//NaNvarnum:Number=10;trace(num);//10Thecompilerwillnot,however,hoistanyassignmentstatements.
Thisexplainswhytheinitialtrace()ofnumresultsinNaN(notanumber),whichisthedefaultvalueforvariablesoftheNumberdatatype.
Thismeansthatyoucanassignvaluestovariablesevenbeforetheyaredeclared,asshowninthefollowingexample:num=5;trace(num);//5varnum:Number=10;trace(num);//10DefaultvaluesAdefaultvalueisthevaluethatavariablecontainsbeforeyousetitsvalue.
Youinitializeavariablewhenyousetitsvalueforthefirsttime.
Ifyoudeclareavariable,butdonotsetitsvalue,thatvariableisuninitialized.
Thevalueofanuninitializedvariabledependsonitsdatatype.
Thefollowingtabledescribesthedefaultvaluesofvariables,organizedbydatatype:DatatypeDefaultvalueBooleanfalseint0NumberNaNObjectnullStringnull47LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011ForvariablesoftypeNumber,thedefaultvalueisNaN(notanumber),whichisaspecialvaluedefinedbytheIEEE-754standardtomeanavaluethatdoesnotrepresentanumber.
Ifyoudeclareavariable,butdonotdeclareitsdatatype,thedefaultdatatype*applies,whichactuallymeansthatthevariableisuntyped.
Ifyoualsodonotinitializeanuntypedvariablewithavalue,itsdefaultvalueisundefined.
FordatatypesotherthanBoolean,Number,int,anduint,thedefaultvalueofanyuninitializedvariableisnull.
ThisappliestoalltheclassesdefinedbyActionScript3.
0,aswellasanycustomclassesthatyoucreate.
ThevaluenullisnotavalidvalueforvariablesoftypeBoolean,Number,int,oruint.
Ifyouattempttoassignavalueofnulltoasuchavariable,thevalueisconvertedtothedefaultvalueforthatdatatype.
ForvariablesoftypeObject,youcanassignavalueofnull.
IfyouattempttoassignthevalueundefinedtoavariableoftypeObject,thevalueisconvertedtonull.
ForvariablesoftypeNumber,thereisaspecialtop-levelfunctionnamedisNaN()thatreturnstheBooleanvaluetrueifthevariableisnotanumber,andfalseotherwise.
DatatypesAdatatypedefinesasetofvalues.
Forexample,theBooleandatatypeisthesetofexactlytwovalues:trueandfalse.
InadditiontotheBooleandatatype,ActionScript3.
0definesseveralmorecommonlyuseddatatypes,suchasString,Number,andArray.
Youcandefineyourowndatatypesbyusingclassesorinterfacestodefineacustomsetofvalues.
AllvaluesinActionScript3.
0,whethertheyareprimitiveorcomplex,areobjects.
Aprimitivevalueisavaluethatbelongstooneofthefollowingdatatypes:Boolean,int,Number,String,anduint.
Workingwithprimitivevaluesisusuallyfasterthanworkingwithcomplexvalues,becauseActionScriptstoresprimitivevaluesinaspecialwaythatmakesmemoryandspeedoptimizationspossible.
Note:Forreadersinterestedinthetechnicaldetails,ActionScriptstoresprimitivevaluesinternallyasimmutableobjects.
Thefactthattheyarestoredasimmutableobjectsmeansthatpassingbyreferenceiseffectivelythesameaspassingbyvalue.
Thiscutsdownonmemoryusageandincreasesexecutionspeed,becausereferencesareusuallysignificantlysmallerthanthevaluesthemselves.
Acomplexvalueisavaluethatisnotaprimitivevalue.
DatatypesthatdefinesetsofcomplexvaluesincludeArray,Date,Error,Function,RegExp,XML,andXMLList.
Manyprogramminglanguagesdistinguishbetweenprimitivevaluesandtheirwrapperobjects.
Java,forexample,hasanintprimitiveandthejava.
lang.
Integerclassthatwrapsit.
Javaprimitivesarenotobjects,buttheirwrappersare,whichmakesprimitivesusefulforsomeoperations,andwrapperobjectsbettersuitedforotheroperations.
InActionScript3.
0,primitivevaluesandtheirwrapperobjectsare,forpracticalpurposes,indistinguishable.
Allvalues,evenprimitivevalues,areobjects.
Theruntimetreatstheseprimitivetypesasspecialcasesthatbehavelikeobjectsbutthatdon'trequirethenormaloverheadassociatedwithcreatingobjects.
Thismeansthatthefollowingtwolinesofcodeareequivalent:varsomeInt:int=3;varsomeInt:int=newint(3);uint0Notdeclared(equivalenttotypeannotation*)undefinedAllotherclasses,includinguser-definedclasses.
nullDatatypeDefaultvalue48LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011AlltheprimitiveandcomplexdatatypeslistedabovearedefinedbytheActionScript3.
0coreclasses.
Thecoreclassesallowyoutocreateobjectsusingliteralvaluesinsteadofusingthenewoperator.
Forexample,youcancreateanarrayusingaliteralvalueortheArrayclassconstructor,asfollows:varsomeArray:Array=[1,2,3];//literalvaluevarsomeArray:Array=newArray(1,2,3);//ArrayconstructorTypecheckingTypecheckingcanoccurateithercompiletimeorruntime.
Staticallytypedlanguages,suchasC++andJava,dotypecheckingatcompiletime.
Dynamicallytypedlanguages,suchasSmalltalkandPython,handletypecheckingatruntime.
Asadynamicallytypedlanguage,ActionScript3.
0hasrun-timetypechecking,butalsosupportscompile-timetypecheckingwithaspecialcompilermodecalledstrictmode.
Instrictmode,typecheckingoccursatbothcompiletimeandruntime,butinstandardmode,typecheckingoccursonlyatruntime.
Dynamicallytypedlanguagesoffertremendousflexibilitywhenyoustructureyourcode,butatthecostofallowingtypeerrorstomanifestatruntime.
Staticallytypedlanguagesreporttypeerrorsatcompiletime,butatthecostofrequiringthattypeinformationbeknownatcompiletime.
Compile-timetypecheckingCompile-timetypecheckingisoftenfavoredinlargerprojectsbecauseasthesizeofaprojectgrows,datatypeflexibilityusuallybecomeslessimportantthancatchingtypeerrorsasearlyaspossible.
Thisiswhy,bydefault,theActionScriptcompilerinFlashProfessionalandFlashBuilderissettoruninstrictmode.
AdobeFlashBuilderYoucandisablestrictmodeinFlashBuilderthroughtheActionScriptcompilersettingsintheProjectPropertiesdialogbox.
Toprovidecompile-timetypechecking,thecompilerneedstoknowthedatatypeinformationforthevariablesorexpressionsinyourcode.
Toexplicitlydeclareadatatypeforavariable,addthecolonoperator(:)followedbythedatatypeasasuffixtothevariablename.
Toassociateadatatypewithaparameter,usethecolonoperatorfollowedbythedatatype.
Forexample,thefollowingcodeaddsdatatypeinformationtothexParamparameter,anddeclaresavariablemyParamwithanexplicitdatatype:functionruntimeTest(xParam:String){trace(xParam);}varmyParam:String="hello";runtimeTest(myParam);Instrictmode,theActionScriptcompilerreportstypemismatchesascompilererrors.
Forexample,thefollowingcodedeclaresafunctionparameterxParam,oftypeObject,butlaterattemptstoassignvaluesoftypeStringandNumbertothatparameter.
Thisproducesacompilererrorinstrictmode.
49LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011functiondynamicTest(xParam:Object){if(xParamisString){varmyStr:String=xParam;//compilererrorinstrictmodetrace("String:"+myStr);}elseif(xParamisNumber){varmyNum:Number=xParam;//compilererrorinstrictmodetrace("Number:"+myNum);}}Eveninstrictmode,however,youcanselectivelyoptofoutcompile-timetypecheckingbyleavingtherightsideofanassignmentstatementuntyped.
Youcanmarkavariableorexpressionasuntypedbyeitheromittingatypeannotation,orusingthespecialasterisk(*)typeannotation.
Forexample,ifthexParamparameterinthepreviousexampleismodifiedsothatitnolongerhasatypeannotation,thecodecompilesinstrictmode:functiondynamicTest(xParam){if(xParamisString){varmyStr:String=xParam;trace("String:"+myStr);}elseif(xParamisNumber){varmyNum:Number=xParam;trace("Number:"+myNum);}}dynamicTest(100)dynamicTest("onehundred");Run-timetypecheckingRun-timetypecheckingoccursinActionScript3.
0whetheryoucompileinstrictmodeorstandardmode.
Considerasituationinwhichthevalue3ispassedasanargumenttoafunctionthatexpectsanarray.
Instrictmode,thecompilerwillgenerateanerror,becausethevalue3isnotcompatiblewiththedatatypeArray.
Ifyoudisablestrictmode,andruninstandardmode,thecompilerdoesnotcomplainaboutthetypemismatch,butrun-timetypecheckingresultsinarun-timeerror.
ThefollowingexampleshowsafunctionnamedtypeTest()thatexpectsanArrayargumentbutispassedavalueof3.
Thiscausesarun-timeerrorinstandardmode,becausethevalue3isnotamemberoftheparameter'sdeclareddatatype(Array).
functiontypeTest(xParam:Array){trace(xParam);}varmyNum:Number=3;typeTest(myNum);//run-timeerrorinActionScript3.
0standardmode50LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Theremayalsobesituationswhereyougetarun-timetypeerrorevenwhenyouareoperatinginstrictmode.
Thisispossibleifyouusestrictmode,butoptoutofcompile-timetypecheckingbyusinganuntypedvariable.
Whenyouuseanuntypedvariable,youarenoteliminatingtypecheckingbutratherdeferringituntilruntime.
Forexample,ifthemyNumvariableinthepreviousexampledoesnothaveadeclareddatatype,thecompilercannotdetectthetypemismatch,butthecodewillgeneratearun-timeerrorbecauseitcomparestherun-timevalueofmyNum,whichissetto3asaresultoftheassignmentstatement,withthetypeofxParam,whichissettotheArraydatatype.
functiontypeTest(xParam:Array){trace(xParam);}varmyNum=3;typeTest(myNum);//run-timeerrorinActionScript3.
0Run-timetypecheckingalsoallowsmoreflexibleuseofinheritancethandoescompile-timechecking.
Bydeferringtypecheckingtoruntime,standardmodeallowsyoutoreferencepropertiesofasubclassevenifyouupcast.
Anupcastoccurswhenyouuseabaseclasstodeclarethetypeofaclassinstancebutuseasubclasstoinstantiateit.
Forexample,youcancreateaclassnamedClassBasethatcanbeextended(classeswiththefinalattributecannotbeextended):classClassBase{}YoucansubsequentlycreateasubclassofClassBasenamedClassExtender,whichhasonepropertynamedsomeString,asfollows:classClassExtenderextendsClassBase{varsomeString:String;}Usingbothclasses,youcancreateaclassinstancethatisdeclaredusingtheClassBasedatatype,butinstantiatedusingtheClassExtenderconstructor.
Anupcastisconsideredasafeoperation,becausethebaseclassdoesnotcontainanypropertiesormethodsthatarenotinthesubclass.
varmyClass:ClassBase=newClassExtender();Asubclass,however,doescontainpropertiesormethodsthatitsbaseclassdoesnot.
Forexample,theClassExtenderclasscontainsthesomeStringproperty,whichdoesnotexistintheClassBaseclass.
InActionScript3.
0standardmode,youcanreferencethispropertyusingthemyClassinstancewithoutgeneratingacompile-timeerror,asshowninthefollowingexample:varmyClass:ClassBase=newClassExtender();myClass.
someString="hello";//noerrorinActionScript3.
0standardmodeTheisoperatorTheisoperatorallowsyoutotestwhetheravariableorexpressionisamemberofagivendatatype.
InpreviousversionsofActionScript,theinstanceofoperatorprovidedthisfunctionality,butinActionScript3.
0theinstanceofoperatorshouldnotbeusedtotestfordatatypemembership.
Theisoperatorshouldbeusedinsteadoftheinstanceofoperatorformanualtypechecking,becausetheexpressionxinstanceofymerelycheckstheprototypechainofxfortheexistenceofy(andinActionScript3.
0,theprototypechaindoesnotprovideacompletepictureoftheinheritancehierarchy).
51LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Theisoperatorexaminestheproperinheritancehierarchyandcanbeusedtochecknotonlywhetheranobjectisaninstanceofaparticularclass,butalsowhetheranobjectisaninstanceofaclassthatimplementsaparticularinterface.
ThefollowingexamplecreatesaninstanceoftheSpriteclassnamedmySpriteandusestheisoperatortotestwhethermySpriteisaninstanceoftheSpriteandDisplayObjectclasses,andwhetheritimplementstheIEventDispatcherinterface:varmySprite:Sprite=newSprite();trace(mySpriteisSprite);//truetrace(mySpriteisDisplayObject);//truetrace(mySpriteisIEventDispatcher);//trueTheisoperatorcheckstheinheritancehierarchyandproperlyreportsthatmySpriteiscompatiblewiththeSpriteandDisplayObjectclasses(theSpriteclassisasubclassoftheDisplayObjectclass).
TheisoperatoralsocheckswhethermySpriteinheritsfromanyclassesthatimplementtheIEventDispatcherinterface.
BecausetheSpriteclassinheritsfromtheEventDispatcherclass,whichimplementstheIEventDispatcherinterface,theisoperatorcorrectlyreportsthatmySpriteimplementsthesameinterface.
Thefollowingexampleshowsthesametestsfromthepreviousexample,butwithinstanceofinsteadoftheisoperator.
TheinstanceofoperatorcorrectlyidentifiesthatmySpriteisaninstanceofSpriteorDisplayObject,butitreturnsfalsewhenusedtotestwhethermySpriteimplementstheIEventDispatcherinterface.
trace(mySpriteinstanceofSprite);//truetrace(mySpriteinstanceofDisplayObject);//truetrace(mySpriteinstanceofIEventDispatcher);//falseTheasoperatorTheasoperatoralsoallowsyoutocheckwhetheranexpressionisamemberofagivendatatype.
Unliketheisoperator,however,theasoperatordoesnotreturnaBooleanvalue.
Rather,theasoperatorreturnsthevalueoftheexpressioninsteadoftrue,andnullinsteadoffalse.
ThefollowingexampleshowstheresultsofusingtheasoperatorinsteadoftheisoperatorinthesimplecaseofcheckingwhetheraSpriteinstanceisamemberoftheDisplayObject,IEventDispatcher,andNumberdatatypes.
varmySprite:Sprite=newSprite();trace(mySpriteasSprite);//[objectSprite]trace(mySpriteasDisplayObject);//[objectSprite]trace(mySpriteasIEventDispatcher);//[objectSprite]trace(mySpriteasNumber);//nullWhenyouusetheasoperator,theoperandontherightmustbeadatatype.
Anattempttouseanexpressionotherthanadatatypeastheoperandontherightwillresultinanerror.
DynamicclassesAdynamicclassdefinesanobjectthatcanbealteredatruntimebyaddingorchangingpropertiesandmethods.
Aclassthatisnotdynamic,suchastheStringclass,isasealedclass.
Youcannotaddpropertiesormethodstoasealedclassatruntime.
Youcreatedynamicclassesbyusingthedynamicattributewhenyoudeclareaclass.
Forexample,thefollowingcodecreatesadynamicclassnamedProtean:52LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011dynamicclassProtean{privatevarprivateGreeting:String="hi";publicvarpublicGreeting:String="hello";functionProtean(){trace("Proteaninstancecreated");}}IfyoulaterinstantiateaninstanceoftheProteanclass,youcanaddpropertiesormethodstoitoutsidetheclassdefinition.
Forexample,thefollowingcodecreatesaninstanceoftheProteanclassandaddsapropertynamedaStringandapropertynamedaNumbertotheinstance:varmyProtean:Protean=newProtean();myProtean.
aString="testing";myProtean.
aNumber=3;trace(myProtean.
aString,myProtean.
aNumber);//testing3Propertiesthatyouaddtoaninstanceofadynamicclassarerun-timeentities,soanytypecheckingisdoneatruntime.
Youcannotaddatypeannotationtoapropertythatyouaddinthismanner.
YoucanalsoaddamethodtothemyProteaninstancebydefiningafunctionandattachingthefunctiontoapropertyofthemyProteaninstance.
ThefollowingcodemovesthetracestatementintoamethodnamedtraceProtean():varmyProtean:Protean=newProtean();myProtean.
aString="testing";myProtean.
aNumber=3;myProtean.
traceProtean=function(){trace(this.
aString,this.
aNumber);};myProtean.
traceProtean();//testing3Methodscreatedinthisway,however,donothaveaccesstoanyprivatepropertiesormethodsoftheProteanclass.
Moreover,evenreferencestopublicpropertiesormethodsoftheProteanclassmustbequalifiedwitheitherthethiskeywordortheclassname.
ThefollowingexampleshowsthetraceProtean()methodattemptingtoaccesstheprivateandpublicvariablesoftheProteanclass.
myProtean.
traceProtean=function(){trace(myProtean.
privateGreeting);//undefinedtrace(myProtean.
publicGreeting);//hello};myProtean.
traceProtean();DatatypedescriptionsTheprimitivedatatypesincludeBoolean,int,Null,Number,String,uint,andvoid.
TheActionScriptcoreclassesalsodefinethefollowingcomplexdatatypes:Object,Array,Date,Error,Function,RegExp,XML,andXMLList.
BooleandatatypeTheBooleandatatypeincludestwovalues:trueandfalse.
NoothervaluesarevalidforvariablesofBooleantype.
ThedefaultvalueofaBooleanvariablethathasbeendeclaredbutnotinitializedisfalse.
53LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011intdatatypeTheintdatatypeisstoredinternallyasa32-bitintegerandincludesthesetofintegersfrom-2,147,483,648(-231)to2,147,483,647(231-1),inclusive.
PreviousversionsofActionScriptofferedonlytheNumberdatatype,whichwasusedforbothintegersandfloating-pointnumbers.
InActionScript3.
0,younowhaveaccesstolow-levelmachinetypesfor32-bitsignedandunsignedintegers.
Ifyourvariabledoesnotneedfloating-pointnumbers,usingtheintdatatypeinsteadoftheNumberdatatypeisfasterandmoreefficient.
Forintegervaluesoutsidetherangeoftheminimumandmaximumintvalues,usetheNumberdatatype,whichcanhandlevaluesbetweenpositiveandnegative9,007,199,254,740,992(53-bitintegervalues).
Thedefaultvalueforvariablesthatareofthedatatypeintis0.
NulldatatypeTheNulldatatypecontainsonlyonevalue,null.
ThisisthedefaultvaluefortheStringdatatypeandallclassesthatdefinecomplexdatatypes,includingtheObjectclass.
Noneoftheotherprimitivedatatypes,suchasBoolean,Number,int,anduint,containthevaluenull.
Atruntime,thevaluenullisconvertedtotheappropriatedefaultvalueifyouattempttoassignnulltovariablesoftypeBoolean,Number,int,oruint.
Youcannotusethisdatatypeasatypeannotation.
NumberdatatypeInActionScript3.
0,theNumberdatatypecanrepresentintegers,unsignedintegers,andfloating-pointnumbers.
However,tomaximizeperformance,youshouldusetheNumberdatatypeonlyforintegervalueslargerthanthe32-bitintanduinttypescanstoreorforfloating-pointnumbers.
Tostoreafloating-pointnumber,includeadecimalpointinthenumber.
Ifyouomitadecimalpoint,thenumberisstoredasaninteger.
TheNumberdatatypeusesthe64-bitdouble-precisionformatasspecifiedbytheIEEEStandardforBinaryFloating-PointArithmetic(IEEE-754).
Thisstandarddictateshowfloating-pointnumbersarestoredusingthe64availablebits.
Onebitisusedtodesignatewhetherthenumberispositiveornegative.
Elevenbitsareusedfortheexponent,whichisstoredasbase2.
Theremaining52bitsareusedtostorethesignificand(alsocalledthemantissa),whichisthenumberthatisraisedtothepowerindicatedbytheexponent.
Byusingsomeofitsbitstostoreanexponent,theNumberdatatypecanstorefloating-pointnumberssignificantlylargerthanifitusedallofitsbitsforthesignificand.
Forexample,iftheNumberdatatypeusedall64bitstostorethesignificand,itcouldstoreanumberaslargeas265-1.
Byusing11bitstostoreanexponent,theNumberdatatypecanraiseitssignificandtoapowerof21023.
ThemaximumandminimumvaluesthattheNumbertypecanrepresentarestoredinstaticpropertiesoftheNumberclasscalledNumber.
MAX_VALUEandNumber.
MIN_VALUE.
Number.
MAX_VALUE==1.
79769313486231e+308Number.
MIN_VALUE==4.
940656458412467e-324Althoughthisrangeofnumbersisenormous,thecostofthisrangeisprecision.
TheNumberdatatypeuses52bitstostorethesignificand,withtheresultthatnumbersthatrequiremorethan52bitstorepresentprecisely,suchasthefraction1/3,areonlyapproximations.
Ifyourapplicationrequiresabsoluteprecisionwithdecimalnumbers,youneedtousesoftwarethatimplementsdecimalfloating-pointarithmeticasopposedtobinaryfloating-pointarithmetic.
WhenyoustoreintegervalueswiththeNumberdatatype,onlythe52bitsofthesignificandareused.
TheNumberdatatypeusesthese52bitsandaspecialhiddenbittorepresentintegersfrom-9,007,199,254,740,992(-253)to9,007,199,254,740,992(253).
TheNaNvalueisnotonlyusedasthedefaultvalueforvariablesoftypeNumber,butalsoastheresultofanyoperationthatshouldreturnanumberbutdoesnot.
Forexample,ifyouattempttocalculatethesquarerootofanegativenumber,theresultisNaN.
OtherspecialNumbervaluesincludepositiveinfinityandnegativeinfinity.
54LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Note:Theresultofdivisionby0isonlyNaNifthedivisorisalso0.
Divisionby0producesinfinitywhenthedividendispositiveor-infinitywhenthedividendisnegative.
StringdatatypeTheStringdatatyperepresentsasequenceof16-bitcharacters.
StringsarestoredinternallyasUnicodecharacters,usingtheUTF-16format.
Stringsareimmutablevalues,justastheyareintheJavaprogramminglanguage.
AnoperationonaStringvaluereturnsanewinstanceofthestring.
ThedefaultvalueforavariabledeclaredwiththeStringdatatypeisnull.
Thevaluenullisnotthesameastheemptystring("").
Thevaluenullmeansthatthevariablehasnovaluestoredinit,whiletheemptystringmeansthatthevariablehasavaluethatisaStringcontainingnocharacters.
uintdatatypeTheuintdatatypeisstoredinternallyasa32-bitunsignedintegerandincludesthesetofintegersfrom0to4,294,967,295(232-1),inclusive.
Usetheuintdatatypeforspecialcircumstancesthatcallfornon-negativeintegers.
Forexample,youmustusetheuintdatatypetorepresentpixelcolorvalues,becausetheintdatatypehasaninternalsignbitthatisnotappropriateforhandlingcolorvalues.
Forintegervalueslargerthanthemaximumuintvalue,usetheNumberdatatype,whichcanhandle53-bitintegervalues.
Thedefaultvalueforvariablesthatareofdatatypeuintis0.
voiddatatypeThevoiddatatypecontainsonlyonevalue,undefined.
InpreviousversionsofActionScript,undefinedwasthedefaultvalueforinstancesoftheObjectclass.
InActionScript3.
0,thedefaultvalueforObjectinstancesisnull.
IfyouattempttoassignthevalueundefinedtoaninstanceoftheObjectclass,thevalueisconvertedtonull.
Youcanonlyassignavalueofundefinedtovariablesthatareuntyped.
Untypedvariablesarevariablesthateitherlackanytypeannotation,orusetheasterisk(*)symbolfortypeannotation.
Youcanusevoidonlyasareturntypeannotation.
ObjectdatatypeTheObjectdatatypeisdefinedbytheObjectclass.
TheObjectclassservesasthebaseclassforallclassdefinitionsinActionScript.
TheActionScript3.
0versionoftheObjectdatatypediffersfromthatofpreviousversionsinthreeways.
First,theObjectdatatypeisnolongerthedefaultdatatypeassignedtovariableswithnotypeannotation.
Second,theObjectdatatypenolongerincludesthevalueundefined,whichusedtobethedefaultvalueofObjectinstances.
Third,inActionScript3.
0,thedefaultvalueforinstancesoftheObjectclassisnull.
InpreviousversionsofActionScript,avariablewithnotypeannotationwasautomaticallyassignedtheObjectdatatype.
ThisisnolongertrueinActionScript3.
0,whichnowincludestheideaofatrulyuntypedvariable.
Variableswithnotypeannotationarenowconsidereduntyped.
Ifyouprefertomakeitcleartoreadersofyourcodethatyourintentionistoleaveavariableuntyped,youcanusetheasterisk(*)symbolforthetypeannotation,whichisequivalenttoomittingatypeannotation.
Thefollowingexampleshowstwoequivalentstatements,bothofwhichdeclareanuntypedvariablex:varxvarx:*Onlyuntypedvariablescanholdthevalueundefined.
Ifyouattempttoassignthevalueundefinedtoavariablethathasadatatype,theruntimeconvertsthevalueundefinedtothedefaultvalueofthatdatatype.
ForinstancesoftheObjectdatatype,thedefaultvalueisnull,whichmeansthatifyouattempttoassignundefinedtoanObjectinstancethevalueisconvertedtonull.
55LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011TypeconversionsAtypeconversionissaidtooccurwhenavalueistransformedintoavalueofadifferentdatatype.
Typeconversionscanbeeitherimplicitorexplicit.
Implicitconversion,whichisalsocalledcoercion,issometimesperformedatruntime.
Forexample,ifthevalue2isassignedtoavariableoftheBooleandatatype,thevalue2isconvertedtotheBooleanvaluetruebeforeassigningthevaluetothevariable.
Explicitconversion,whichisalsocalledcasting,occurswhenyourcodeinstructsthecompilertotreatavariableofonedatatypeasifitbelongstoadifferentdatatype.
Whenprimitivevaluesareinvolved,castingactuallyconvertsvaluesfromonedatatypetoanother.
Tocastanobjecttoadifferenttype,youwraptheobjectnameinparenthesesandprecedeitwiththenameofthenewtype.
Forexample,thefollowingcodetakesaBooleanvalueandcastsittoaninteger:varmyBoolean:Boolean=true;varmyINT:int=int(myBoolean);trace(myINT);//1ImplicitconversionsImplicitconversionshappenatruntimeinanumberofcontexts:InassignmentstatementsWhenvaluesarepassedasfunctionargumentsWhenvaluesarereturnedfromfunctionsInexpressionsusingcertainoperators,suchastheaddition(+)operatorForuser-definedtypes,implicitconversionssucceedwhenthevaluetobeconvertedisaninstanceofthedestinationclassoraclassthatderivesfromthedestinationclass.
Ifanimplicitconversionisunsuccessful,anerroroccurs.
Forexample,thefollowingcodecontainsasuccessfulimplicitconversionandanunsuccessfulimplicitconversion:classA{}classBextendsA{}varobjA:A=newA();varobjB:B=newB();vararr:Array=newArray();objA=objB;//Conversionsucceeds.
objB=arr;//Conversionfails.
Forprimitivetypes,implicitconversionsarehandledbycallingthesameinternalconversionalgorithmsthatarecalledbytheexplicitconversionfunctions.
ExplicitconversionsIt'shelpfultouseexplicitconversions,orcasting,whenyoucompileinstrictmode,becausetheremaybetimeswhenyoudonotwantatypemismatchtogenerateacompile-timeerror.
Thismaybethecasewhenyouknowthatcoercionwillconvertyourvaluescorrectlyatruntime.
Forexample,whenworkingwithdatareceivedfromaform,youmaywanttorelyoncoerciontoconvertcertainstringvaluestonumericvalues.
Thefollowingcodegeneratesacompile-timeerroreventhoughthecodewouldruncorrectlyinstandardmode:varquantityField:String="3";varquantity:int=quantityField;//compiletimeerrorinstrictmodeIfyouwanttocontinueusingstrictmode,butwouldlikethestringconvertedtoaninteger,youcanuseexplicitconversion,asfollows:56LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011varquantityField:String="3";varquantity:int=int(quantityField);//Explicitconversionsucceeds.
Castingtoint,uint,andNumberYoucancastanydatatypeintooneofthethreenumbertypes:int,uint,andNumber.
Ifthenumbercan'tbeconvertedforsomereason,thedefaultvalueof0isassignedfortheintanduintdatatypes,andthedefaultvalueofNaNisassignedfortheNumberdatatype.
IfyouconvertaBooleanvaluetoanumber,truebecomesthevalue1andfalsebecomesthevalue0.
varmyBoolean:Boolean=true;varmyUINT:uint=uint(myBoolean);varmyINT:int=int(myBoolean);varmyNum:Number=Number(myBoolean);trace(myUINT,myINT,myNum);//111myBoolean=false;myUINT=uint(myBoolean);myINT=int(myBoolean);myNum=Number(myBoolean);trace(myUINT,myINT,myNum);//000Stringvaluesthatcontainonlydigitscanbesuccessfullyconvertedintooneofthenumbertypes.
Thenumbertypescanalsoconvertstringsthatlooklikenegativenumbersorstringsthatrepresentahexadecimalvalue(forexample,0x1A).
Theconversionprocessignoresleadingandtrailingwhitespacecharactersinthestringvalue.
Youcanalsocaststringsthatlooklikefloating-pointnumbersusingNumber().
Theinclusionofadecimalpointcausesuint()andint()toreturnaninteger,truncatingthedecimalandthecharactersfollowingit.
Forexample,thefollowingstringvaluescanbecastintonumbers:trace(uint("5"));//5trace(uint("-5"));//4294967291.
ItwrapsaroundfromMAX_VALUEtrace(uint("27"));//27trace(uint("3.
7"));//3trace(int("3.
7"));//3trace(int("0x1A"));//26trace(Number("3.
7"));//3.
7Stringvaluesthatcontainnon-numericcharactersreturn0whencastwithint()oruint()andNaNwhencastwithNumber().
Theconversionprocessignoresleadingandtrailingwhitespace,butreturns0orNaNifastringhaswhitespaceseparatingtwonumbers.
trace(uint("5a"));//0trace(uint("ten"));//0trace(uint("1763"));//0InActionScript3.
0,theNumber()functionnolongersupportsoctal,orbase8,numbers.
IfyousupplyastringwithaleadingzerototheActionScript2.
0Number()function,thenumberisinterpretedasanoctalnumber,andconvertedtoitsdecimalequivalent.
ThisisnottruewiththeNumber()functioninActionScript3.
0,whichinsteadignorestheleadingzero.
Forexample,thefollowingcodegeneratesdifferentoutputwhencompiledusingdifferentversionsofActionScript:trace(Number("044"));//ActionScript3.
044//ActionScript2.
036Castingisnotnecessarywhenavalueofonenumerictypeisassignedtoavariableofadifferentnumerictype.
Eveninstrictmode,thenumerictypesareimplicitlyconvertedtotheothernumerictypes.
Thismeansthatinsomecases,unexpectedvaluesmayresultwhentherangeofatypeisexceeded.
Thefollowingexamplesallcompileinstrictmode,thoughsomegenerateunexpectedvalues:57LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011varmyUInt:uint=-3;//Assignint/Numbervaluetouintvariabletrace(myUInt);//4294967293varmyNum:Number=sampleUINT;//Assignint/uintvaluetoNumbervariabletrace(myNum)//4294967293varmyInt:int=uint.
MAX_VALUE+1;//AssignNumbervaluetouintvariabletrace(myInt);//0myInt=int.
MAX_VALUE+1;//Assignuint/Numbervaluetointvariabletrace(myInt);//-2147483648ThefollowingtablesummarizestheresultsofcastingtotheNumber,int,oruintdatatypefromotherdatatypes.
CastingtoBooleanCastingtoBooleanfromanyofthenumericdatatypes(uint,int,andNumber)resultsinfalseifthenumericvalueis0,andtrueotherwise.
FortheNumberdatatype,thevalueNaNalsoresultsinfalse.
Thefollowingexampleshowstheresultsofcastingthenumbers-1,0,and1:varmyNum:Number;for(myNum=-1;myNum3:Stringwhitespaceonlytrace(Boolean(str3));//trueCastingtoBooleanfromaninstanceoftheObjectclassreturnsfalseiftheinstanceisnull;otherwise,itreturnstrue:DatatypeorvalueResultofconversiontoNumber,int,oruintBooleanIfthevalueistrue,1;otherwise,0.
DateTheinternalrepresentationoftheDateobject,whichisthenumberofmillisecondssincemidnightJanuary1,1970,universaltime.
null0ObjectIftheinstanceisnullandconvertedtoNumber,NaN;otherwise,0.
StringAnumberifthestringcanbeconvertedtoanumber;otherwise,NaNifconvertedtoNumber,or0ifconvertedtointoruint.
undefinedIfconvertedtoNumber,NaN;ifconvertedtointoruint,0.
58LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011varmyObj:Object;//Uninitializedobjectisnull.
trace(Boolean(myObj));//falsemyObj=newObject();//instantiatetrace(Boolean(myObj));//trueBooleanvariablesgetspecialtreatmentinstrictmodeinthatyoucanassignvaluesofanydatatypetoaBooleanvariablewithoutcasting.
ImplicitcoercionfromalldatatypestotheBooleandatatypeoccurseveninstrictmode.
Inotherwords,unlikealmostallotherdatatypes,castingtoBooleanisnotnecessarytoavoidstrictmodeerrors.
Thefollowingexamplesallcompileinstrictmodeandbehaveasexpectedatruntime:varmyObj:Object=newObject();//instantiatevarbool:Boolean=myObj;trace(bool);//truebool="randomstring";trace(bool);//truebool=newArray();trace(bool);//truebool=NaN;trace(bool);//falseThefollowingtablesummarizestheresultsofcastingtotheBooleandatatypefromotherdatatypes:CastingtoStringCastingtotheStringdatatypefromanyofthenumericdatatypesreturnsastringrepresentationofthenumber.
CastingtotheStringdatatypefromaBooleanvaluereturnsthestring"true"ifthevalueistrue,andreturnsthestring"false"ifthevalueisfalse.
CastingtotheStringdatatypefromaninstanceoftheObjectclassreturnsthestring"null"iftheinstanceisnull.
Otherwise,castingtotheStringtypefromtheObjectclassreturnsthestring"[objectObject]".
CastingtoStringfromaninstanceoftheArrayclassreturnsastringmadeupofacomma-delimitedlistofallthearrayelements.
Forexample,thefollowingcasttotheStringdatatypereturnsonestringcontainingallthreeelementsofthearray:varmyArray:Array=["primary","secondary","tertiary"];trace(String(myArray));//primary,secondary,tertiaryCastingtoStringfromaninstanceoftheDateclassreturnsastringrepresentationofthedatethattheinstancecontains.
Forexample,thefollowingexamplereturnsastringrepresentationoftheDateclassinstance(theoutputshowsresultforPacificDaylightTime):varmyDate:Date=newDate(2005,6,1);trace(String(myDate));//FriJul100:00:00GMT-07002005ThefollowingtablesummarizestheresultsofcastingtotheStringdatatypefromotherdatatypes.
DatatypeorvalueResultofconversiontoBooleanStringfalseifthevalueisnullortheemptystring("");trueotherwise.
nullfalseNumber,int,oruintfalseifthevalueisNaNor0;trueotherwise.
Objectfalseiftheinstanceisnull;trueotherwise.
59LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011SyntaxThesyntaxofalanguagedefinesasetofrulesthatmustbefollowedwhenwritingexecutablecode.
CasesensitivityActionScript3.
0isacase-sensitivelanguage.
Identifiersthatdifferonlyincaseareconsidereddifferentidentifiers.
Forexample,thefollowingcodecreatestwodifferentvariables:varnum1:int;varNum1:int;DotsyntaxThedotoperator(.
)providesawaytoaccessthepropertiesandmethodsofanobject.
Usingdotsyntax,youcanrefertoaclasspropertyormethodbyusinganinstancename,followedbythedotoperatorandnameofthepropertyormethod.
Forexample,considerthefollowingclassdefinition:classDotExample{publicvarprop1:String;publicfunctionmethod1():void{}}Usingdotsyntax,youcanaccesstheprop1propertyandthemethod1()methodbyusingtheinstancenamecreatedinthefollowingcode:varmyDotEx:DotExample=newDotExample();myDotEx.
prop1="hello";myDotEx.
method1();Youcanusedotsyntaxwhenyoudefinepackages.
Youusethedotoperatortorefertonestedpackages.
Forexample,theEventDispatcherclassresidesinapackagenamedeventsthatisnestedwithinthepackagenamedflash.
Youcanrefertotheeventspackageusingthefollowingexpression:flash.
eventsYoucanalsorefertotheEventDispatcherclassusingthisexpression:flash.
events.
EventDispatcherDatatypeorvalueResultofconversiontostringArrayAstringmadeupofallarrayelements.
Boolean"true"or"false"DateAstringrepresentationoftheDateobject.
null"null"Number,int,oruintAstringrepresentationofthenumber.
ObjectIftheinstanceisnull,"null";otherwise,"[objectObject]".
60LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011SlashsyntaxSlashsyntaxisnotsupportedinActionScript3.
0.
SlashsyntaxwasusedinearlierversionsofActionScripttoindicatethepathofamoviecliporvariable.
LiteralsAliteralisavaluethatappearsdirectlyinyourcode.
Thefollowingexamplesareallliterals:17"hello"-39.
4nullundefinedtruefalseLiteralscanalsobegroupedtoformcompoundliterals.
Arrayliteralsareenclosedinbracketcharacters([])andusethecommatoseparatearrayelements.
Anarrayliteralcanbeusedtoinitializeanarray.
Thefollowingexamplesshowtwoarraysthatareinitializedusingarrayliterals.
YoucanusethenewstatementandpassthecompoundliteralasaparametertotheArrayclassconstructor,butyoucanalsoassignliteralvaluesdirectlywheninstantiatinginstancesofthefollowingActionScriptcoreclasses:Object,Array,String,Number,int,uint,XML,XMLList,andBoolean.
//Usenewstatement.
varmyStrings:Array=newArray(["alpha","beta","gamma"]);varmyNums:Array=newArray([1,2,3,5,8]);//Assignliteraldirectly.
varmyStrings:Array=["alpha","beta","gamma"];varmyNums:Array=[1,2,3,5,8];Literalscanalsobeusedtoinitializeagenericobject.
AgenericobjectisaninstanceoftheObjectclass.
Objectliteralsareenclosedincurlybrackets({})andusethecommatoseparateobjectproperties.
Eachpropertyisdeclaredwiththecoloncharacter(:),whichseparatesthenameofthepropertyfromthevalueoftheproperty.
Youcancreateagenericobjectusingthenewstatement,andpasstheobjectliteralasaparametertotheObjectclassconstructor,oryoucanassigntheobjectliteraldirectlytotheinstanceyouaredeclaring.
Thefollowingexampledemonstratestwoalternativewaystocreateanewgenericobjectandinitializetheobjectwiththreeproperties(propA,propB,andpropC),eachwithvaluessetto1,2,and3,respectively://Usenewstatementandaddproperties.
varmyObject:Object=newObject();myObject.
propA=1;myObject.
propB=2;myObject.
propC=3;//Assignliteraldirectly.
varmyObject:Object={propA:1,propB:2,propC:3};61LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011MoreHelptopicsWorkingwithstringsUsingregularexpressionsInitializingXMLvariablesSemicolonsYoucanusethesemicoloncharacter(;)toterminateastatement.
Alternatively,ifyouomitthesemicoloncharacter,thecompilerassumesthateachlineofcoderepresentsasinglestatement.
Becausemanyprogrammersareaccustomedtousingthesemicolontodenotetheendofastatement,yourcodemaybeeasiertoreadifyouconsistentlyusesemicolonstoterminateyourstatements.
Usingasemicolontoterminateastatementallowsyoutoplacemorethanonestatementonasingleline,butthismaymakeyourcodemoredifficulttoread.
ParenthesesYoucanuseparentheses(())inthreewaysinActionScript3.
0.
First,youcanuseparenthesestochangetheorderofoperationsinanexpression.
Operationsthataregroupedinsideparenthesesarealwaysexecutedfirst.
Forexample,parenthesesareusedtoaltertheorderofoperationsinthefollowingcode:trace(2+3*4);//14trace((2+3)*4);//20Second,youcanuseparentheseswiththecommaoperator(,)toevaluateaseriesofexpressionsandreturntheresultofthefinalexpression,asshowninthefollowingexample:vara:int=2;varb:int=3;trace((a++,b++,a+b));//7Third,youcanuseparenthesestopassoneormoreparameterstofunctionsormethods,asshowninthefollowingexample,whichpassesaStringvaluetothetrace()function:trace("hello");//helloCommentsActionScript3.
0codesupportstwotypesofcomments:single-linecommentsandmultilinecomments.
ThesecommentingmechanismsaresimilartothecommentingmechanismsinC++andJava.
Thecompilerignorestextthatismarkedasacomment.
Single-linecommentsbeginwithtwoforwardslashcharacters(//)andcontinueuntiltheendoftheline.
Forexample,thefollowingcodecontainsasingle-linecomment:varsomeNumber:Number=3;//asinglelinecommentMultilinecommentsbeginwithaforwardslashandasterisk(/*)andendwithanasteriskandforwardslash(*/).
/*Thisismultilinecommentthatcanspanmorethanonelineofcode.
*/62LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011KeywordsandreservedwordsReservedwordsarewordsthatyoucannotuseasidentifiersinyourcodebecausethewordsarereservedforusebyActionScript.
Reservedwordsincludelexicalkeywords,whichareremovedfromtheprogramnamespacebythecompiler.
Thecompilerreportsanerrorifyouusealexicalkeywordasanidentifier.
ThefollowingtablelistsActionScript3.
0lexicalkeywords.
Thereisasmallsetofkeywords,calledsyntactickeywords,thatcanbeusedasidentifiers,butthathavespecialmeaningincertaincontexts.
ThefollowingtablelistsActionScript3.
0syntactickeywords.
Therearealsoseveralidentifiersthataresometimesreferredtoasfuturereservedwords.
TheseidentifiersarenotreservedbyActionScript3.
0,thoughsomeofthemmaybetreatedaskeywordsbysoftwarethatincorporatesActionScript3.
0.
Youmightbeabletousemanyoftheseidentifiersinyourcode,butAdoberecommendsthatyoudonotusethembecausetheymayappearaskeywordsinasubsequentversionofthelanguage.
asbreakcasecatchclassconstcontinuedefaultdeletedoelseextendsfalsefinallyforfunctionifimplementsimportininstanceofinterfaceinternalisnativenewnullpackageprivateprotectedpublicreturnsuperswitchthisthrowtotruetrytypeofusevarvoidwhilewitheachgetsetnamespaceincludedynamicfinalnativeoverridestaticabstractbooleanbytecastchardebuggerdoubleenumexportfloatgotointrinsiclongprototypeshortsynchronizedthrowstotransienttypevirtualvolatile63LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011ConstantsActionScript3.
0supportstheconststatement,whichyoucanusetocreateconstants.
Constantsarepropertieswithafixedvaluethatcannotbealtered.
Youcanassignavaluetoaconstantonlyonce,andtheassignmentmustoccurincloseproximitytothedeclarationoftheconstant.
Forexample,ifaconstantisdeclaredasamemberofaclass,youcanassignavaluetothatconstantonlyaspartofthedeclarationorinsidetheclassconstructor.
Thefollowingcodedeclarestwoconstants.
Thefirstconstant,MINIMUM,hasavalueassignedaspartofthedeclarationstatement.
Thesecondconstant,MAXIMUM,hasavalueassignedintheconstructor.
Notethatthisexampleonlycompilesinstandardmodebecausestrictmodeonlyallowsaconstant'svaluetobeassignedatinitializationtime.
classA{publicconstMINIMUM:int=0;publicconstMAXIMUM:int;publicfunctionA(){MAXIMUM=10;}}vara:A=newA();trace(a.
MINIMUM);//0trace(a.
MAXIMUM);//10Anerrorresultsifyouattempttoassignaninitialvaluetoaconstantinanyotherway.
Forexample,ifyouattempttosettheinitialvalueofMAXIMUMoutsidetheclass,arun-timeerroroccurs.
classA{publicconstMINIMUM:int=0;publicconstMAXIMUM:int;}vara:A=newA();a["MAXIMUM"]=10;//run-timeerrorActionScript3.
0definesawiderangeofconstantsforyouruse.
Byconvention,constantsinActionScriptuseallcapitalletters,withwordsseparatedbytheunderscorecharacter(_).
Forexample,theMouseEventclassdefinitionusesthisnamingconventionforitsconstants,eachofwhichrepresentsaneventrelatedtomouseinput:packageflash.
events{publicclassMouseEventextendsEvent{publicstaticconstCLICK:String="click";publicstaticconstDOUBLE_CLICK:String="doubleClick";publicstaticconstMOUSE_DOWN:String="mouseDown";publicstaticconstMOUSE_MOVE:String="mouseMove";.
.
.
}}64LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011OperatorsOperatorsarespecialfunctionsthattakeoneormoreoperandsandreturnavalue.
Anoperandisavalue—usuallyaliteral,avariable,oranexpression—thatanoperatorusesasinput.
Forexample,inthefollowingcode,theaddition(+)andmultiplication(*)operatorsareusedwiththreeliteraloperands(2,3,and4)toreturnavalue.
Thisvalueisthenusedbytheassignment(=)operatortoassignthereturnedvalue,14,tothevariablesumNumber.
varsumNumber:uint=2+3*4;//uint=14Operatorscanbeunary,binary,orternary.
Aunaryoperatortakesoneoperand.
Forexample,theincrement(++)operatorisaunaryoperator,becauseittakesonlyoneoperand.
Abinaryoperatortakestwooperands.
Forexample,thedivision(/)operatortakestwooperands.
Aternaryoperatortakesthreeoperands.
Forexample,theconditional(:)operatortakesthreeoperands.
Someoperatorsareoverloaded,whichmeansthattheybehavedifferentlydependingonthetypeorquantityofoperandspassedtothem.
Theaddition(+)operatorisanexampleofanoverloadedoperatorthatbehavesdifferentlydependingonthedatatypeoftheoperands.
Ifbothoperandsarenumbers,theadditionoperatorreturnsthesumofthevalues.
Ifbothoperandsarestrings,theadditionoperatorreturnstheconcatenationofthetwooperands.
Thefollowingexamplecodeshowshowtheoperatorbehavesdifferentlydependingontheoperands:trace(5+5);//10trace("5"+"5");//55Operatorscanalsobehavedifferentlybasedonthenumberofoperandssupplied.
Thesubtraction(-)operatorisbothaunaryandbinaryoperator.
Whensuppliedwithonlyoneoperand,thesubtractionoperatornegatestheoperandandreturnstheresult.
Whensuppliedwithtwooperands,thesubtractionoperatorreturnsthedifferencebetweentheoperands.
Thefollowingexampleshowsthesubtractionoperatorusedfirstasaunaryoperator,andthenasabinaryoperator.
trace(-3);//-3trace(7-2);//5OperatorprecedenceandassociativityOperatorprecedenceandassociativitydeterminetheorderinwhichoperatorsareprocessed.
Althoughitmayseemnaturaltothosefamiliarwitharithmeticthatthecompilerprocessesthemultiplication(*)operatorbeforetheaddition(+)operator,thecompilerneedsexplicitinstructionsaboutwhichoperatorstoprocessfirst.
Suchinstructionsarecollectivelyreferredtoasoperatorprecedence.
ActionScriptdefinesadefaultoperatorprecedencethatyoucanalterusingtheparentheses(())operator.
Forexample,thefollowingcodealtersthedefaultprecedenceinthepreviousexampletoforcethecompilertoprocesstheadditionoperatorbeforethemultiplicationoperator:varsumNumber:uint=(2+3)*4;//uint==20Youmayencountersituationsinwhichtwoormoreoperatorsofthesameprecedenceappearinthesameexpression.
Inthesecases,thecompilerusestherulesofassociativitytodeterminewhichoperatortoprocessfirst.
Allofthebinaryoperators,excepttheassignmentoperators,areleft-associative,whichmeansthatoperatorsontheleftareprocessedbeforeoperatorsontheright.
Theassignmentoperatorsandtheconditional(:)operatorareright-associative,whichmeansthattheoperatorsontherightareprocessedbeforeoperatorsontheleft.
Forexample,considertheless-than()operators,whichhavethesameprecedence.
Ifbothoperatorsareusedinthesameexpression,theoperatorontheleftisprocessedfirstbecausebothoperatorsareleft-associative.
Thismeansthatthefollowingtwostatementsproducethesameoutput:trace(3>23>2)3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Thegreater-thanoperatorisprocessedfirst,whichresultsinavalueoftrue,becausetheoperand3isgreaterthantheoperand2.
Thevaluetrueisthenpassedtotheless-thanoperatoralongwiththeoperand1.
Thefollowingcoderepresentsthisintermediatestate:trace((true)3>(23.
Thefollowingcoderepresentsthisintermediatestate:trace(3>(false));Thegreater-thanoperatorconvertsthevaluefalsetothenumericvalue0andcomparesthatnumericvaluetotheotheroperand3toreturntrue(thevalue3isgreaterthan0).
trace(3>0);//trueThefollowingtableliststheoperatorsforActionScript3.
0inorderofdecreasingprecedence.
Eachrowofthetablecontainsoperatorsofthesameprecedence.
Eachrowofoperatorshashigherprecedencethantherowappearingbelowitinthetable.
GroupOperatorsPrimary[]{x:y}()f(x)newx.
yx[y]Postfixx++x--Unary++x--x+-~!
deletetypeofvoidMultiplicative*/%Additive+-BitwiseshiftRelationalasininstanceofisEqualityBitwiseAND&BitwiseXOR^BitwiseOR|LogicalAND&&LogicalOR||Conditional:AssignmentComma,66LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011PrimaryoperatorsTheprimaryoperatorsincludethoseusedforcreatingArrayandObjectliterals,groupingexpressions,callingfunctions,instantiatingclassinstances,andaccessingproperties.
Alltheprimaryoperators,aslistedinthefollowingtable,haveequalprecedence.
OperatorsthatarepartoftheE4Xspecificationareindicatedbythe(E4X)notation.
PostfixoperatorsThepostfixoperatorstakeoneoperatorandeitherincrementordecrementthevalue.
Althoughtheseoperatorsareunaryoperators,theyareclassifiedseparatelyfromtherestoftheunaryoperatorsbecauseoftheirhigherprecedenceandspecialbehavior.
Whenapostfixoperatorisusedaspartofalargerexpression,theexpression'svalueisreturnedbeforethepostfixoperatorisprocessed.
Forexample,thefollowingcodeshowshowthevalueoftheexpressionxNum++isreturnedbeforethevalueisincremented:varxNum:Number=0;trace(xNum++);//0trace(xNum);//1Allthepostfixoperators,aslistedinthefollowingtable,haveequalprecedence:UnaryoperatorsTheunaryoperatorstakeoneoperand.
Theincrement(++)anddecrement(--)operatorsinthisgroupareprefixoperators,whichmeansthattheyappearbeforetheoperandinanexpression.
Theprefixoperatorsdifferfromtheirpostfixcounterpartsinthattheincrementordecrementoperationiscompletedbeforethevalueoftheoverallexpressionisreturned.
Forexample,thefollowingcodeshowshowthevalueoftheexpression++xNumisreturnedafterthevalueisincremented:OperatorOperationperformed[]Initializesanarray{x:y}Initializesanobject()Groupsexpressionsf(x)CallsafunctionnewCallsaconstructorx.
yx[y]AccessesapropertyInitializesanXMLListobject(E4X)@Accessesanattribute(E4X)::Qualifiesaname(E4X).
.
AccessesadescendantXMLelement(E4X)OperatorOperationperformed++Increments(postfix)--Decrements(postfix)67LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011varxNum:Number=0;trace(++xNum);//1trace(xNum);//1Alltheunaryoperators,aslistedinthefollowingtable,haveequalprecedence:MultiplicativeoperatorsThemultiplicativeoperatorstaketwooperandsandperformmultiplication,division,ormodulocalculations.
Allthemultiplicativeoperators,aslistedinthefollowingtable,haveequalprecedence:AdditiveoperatorsTheadditiveoperatorstaketwooperandsandperformadditionorsubtractioncalculations.
Alltheadditiveoperators,aslistedinthefollowingtable,haveequalprecedence:BitwiseshiftoperatorsThebitwiseshiftoperatorstaketwooperandsandshiftthebitsofthefirstoperandtotheextentspecifiedbythesecondoperand.
Allthebitwiseshiftoperators,aslistedinthefollowingtable,haveequalprecedence:OperatorOperationperformed++Increments(prefix)--Decrements(prefix)+Unary+-Unary-(negation)!
LogicalNOT~BitwiseNOTdeleteDeletesapropertytypeofReturnstypeinformationvoidReturnsundefinedvalueOperatorOperationperformed*Multiplication/Division%ModuloOperatorOperationperformed+Addition-Subtraction68LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011RelationaloperatorsTherelationaloperatorstaketwooperands,comparetheirvalues,andreturnaBooleanvalue.
Alltherelationaloperators,aslistedinthefollowingtable,haveequalprecedence:EqualityoperatorsTheequalityoperatorstaketwooperands,comparetheirvalues,andreturnaBooleanvalue.
Alltheequalityoperators,aslistedinthefollowingtable,haveequalprecedence:BitwiselogicaloperatorsThebitwiselogicaloperatorstaketwooperandsandperformbit-levellogicaloperations.
Thebitwiselogicaloperatorsdifferinprecedenceandarelistedinthefollowingtableinorderofdecreasingprecedence:OperatorOperationperformed>Bitwiserightshift>>>BitwiseunsignedrightshiftOperatorOperationperformedGreaterthan=GreaterthanorequaltoasChecksdatatypeinChecksforobjectpropertiesinstanceofChecksprototypechainisChecksdatatypeOperatorOperationperformed==Equality!
=Inequality===Strictequality!
==StrictinequalityOperatorOperationperformed&BitwiseAND^BitwiseXOR|BitwiseOR69LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011LogicaloperatorsThelogicaloperatorstaketwooperandsandreturnaBooleanresult.
Thelogicaloperatorsdifferinprecedenceandarelistedinthefollowingtableinorderofdecreasingprecedence:ConditionaloperatorTheconditionaloperatorisaternaryoperator,whichmeansthatittakesthreeoperands.
Theconditionaloperatorisashorthandmethodofapplyingtheif.
.
elseconditionalstatement.
AssignmentoperatorsTheassignmentoperatorstaketwooperandsandassignavaluetooneoperand,basedonthevalueoftheotheroperand.
Alltheassignmentoperators,aslistedinthefollowingtable,haveequalprecedence:ConditionalsActionScript3.
0providesthreebasicconditionalstatementsthatyoucanusetocontrolprogramflow.
OperatorOperationperformed&&LogicalAND||LogicalOROperatorOperationperformed:ConditionalOperatorOperationperformed=Assignment*=Multiplicationassignment/=Divisionassignment%=Moduloassignment+=Additionassignment-=Subtractionassignment>=Bitwiserightshiftassignment>>>=Bitwiseunsignedrightshiftassignment&=BitwiseANDassignment^=BitwiseXORassignment|=BitwiseORassignment70LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011if.
.
elseTheif.
.
elseconditionalstatementallowsyoutotestaconditionandexecuteablockofcodeifthatconditionexists,orexecuteanalternativeblockofcodeiftheconditiondoesnotexist.
Forexample,thefollowingcodetestswhetherthevalueofxexceeds20,generatesatrace()functionifitdoes,orgeneratesadifferenttrace()functionifitdoesnot:if(x>20){trace("xis>20");}else{trace("xis20){trace("xis>20");}elseif(x0)trace("xispositive");elseif(xAdoberecommendsthatyoualwaysusecurlybrackets,becauseunexpectedbehaviorcanoccurifstatementsarelateraddedtoaconditionalstatementthatlackscurlybrackets.
Forexample,inthefollowingcodethevalueofpositiveNumsincreasesby1whetherornottheconditionevaluatestotrue:varx:int;varpositiveNums:int=0;if(x>0)trace("xispositive");positiveNums++;trace(positiveNums);//171LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011switchTheswitchstatementisusefulifyouhaveseveralexecutionpathsthatdependonthesameconditionexpression.
Itprovidesfunctionalitysimilartoalongseriesofif.
.
elseifstatements,butissomewhateasiertoread.
InsteadoftestingaconditionforaBooleanvalue,theswitchstatementevaluatesanexpressionandusestheresulttodeterminewhichblockofcodetoexecute.
Blocksofcodebeginwithacasestatementandendwithabreakstatement.
Forexample,thefollowingswitchstatementprintsthedayoftheweek,basedonthedaynumberreturnedbytheDate.
getDay()method:varsomeDate:Date=newDate();vardayNum:uint=someDate.
getDay();switch(dayNum){case0:trace("Sunday");break;case1:trace("Monday");break;case2:trace("Tuesday");break;case3:trace("Wednesday");break;case4:trace("Thursday");break;case5:trace("Friday");break;case6:trace("Saturday");break;default:trace("Outofrange");break;}LoopingLoopingstatementsallowyoutoperformaspecificblockofcoderepeatedlyusingaseriesofvaluesorvariables.
Adoberecommendsthatyoualwaysenclosetheblockofcodeincurlybrackets({}).
Althoughyoucanomitthecurlybracketsiftheblockofcodecontainsonlyonestatement,thispracticeisnotrecommendedforthesamereasonthatitisnotrecommendedforconditionals:itincreasesthelikelihoodthatstatementsaddedlaterareinadvertentlyexcludedfromtheblockofcode.
Ifyoulateraddastatementthatyouwanttoincludeintheblockofcode,butforgettoaddthenecessarycurlybrackets,thestatementarenotexecutedaspartoftheloop.
72LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011forTheforloopallowsyoutoiteratethroughavariableforaspecificrangeofvalues.
Youmustsupplythreeexpressionsinaforstatement:avariablethatissettoaninitialvalue,aconditionalstatementthatdetermineswhentheloopingends,andanexpressionthatchangesthevalueofthevariablewitheachloop.
Forexample,thefollowingcodeloopsfivetimes.
Thevalueofthevariableistartsat0andendsat4,andtheoutputisthenumbers0through4,eachonitsownline.
vari:int;for(i=0;i30};for(vari:StringinmyObj){trace(imyObj[i]);}//output://x:20//y:30Youcanalsoiteratethroughtheelementsofanarray:varmyArray:Array=["one","two","three"];for(vari:StringinmyArray){trace(myArray[i]);}//output://one//two//threeWhatyoucannotdoisiteratethroughthepropertiesofanobjectifitisaninstanceofasealedclass(includingbuilt-inclassesanduser-definedclasses).
Youcanonlyiteratethroughthepropertiesofadynamicclass.
Evenwithinstancesofdynamicclasses,youcanonlyiteratethroughpropertiesthatareaddeddynamically.
foreach.
.
inTheforeach.
.
inloopiteratesthroughtheitemsofacollection,whichcanbetagsinanXMLorXMLListobject,thevaluesheldbyobjectproperties,ortheelementsofanarray.
Forexample,asthefollowingexcerptshows,youcanuseaforeach.
.
inlooptoiteratethroughthepropertiesofagenericobject,butunlikethefor.
.
inloop,theiteratorvariableinaforeach.
.
inloopcontainsthevalueheldbythepropertyinsteadofthenameoftheproperty:73LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011varmyObj:Object={x:20,y:30};foreach(varnuminmyObj){trace(num);}//output://20//30YoucaniteratethroughanXMLorXMLListobject,asthefollowingexampleshows:varmyXML:XML=JaneSusanJohn;foreach(variteminmyXML.
fname){trace(item);}/*outputJaneSusanJohn*/Youcanalsoiteratethroughtheelementsofanarray,asthisexampleshows:varmyArray:Array=["one","two","three"];foreach(variteminmyArray){trace(item);}//output://one//two//threeYoucannotiteratethroughthepropertiesofanobjectiftheobjectisaninstanceofasealedclass.
Evenforinstancesofdynamicclasses,youcannotiteratethroughanyfixedproperties,whicharepropertiesdefinedaspartoftheclassdefinition.
whileThewhileloopislikeanifstatementthatrepeatsaslongastheconditionistrue.
Forexample,thefollowingcodeproducesthesameoutputastheforloopexample:vari:int=0;while(i3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Onedisadvantageofusingawhileloopinsteadofaforloopisthatinfiniteloopsareeasiertowritewithwhileloops.
Theforloopexamplecodedoesnotcompileifyouomittheexpressionthatincrementsthecountervariable,butthewhileloopexampledoescompileifyouomitthatstep.
Withouttheexpressionthatincrementsi,theloopbecomesaninfiniteloop.
do.
.
whileThedo.
.
whileloopisawhileloopthatguaranteesthatthecodeblockisexecutedatleastonce,becausetheconditionischeckedafterthecodeblockisexecuted.
Thefollowingcodeshowsasimpleexampleofado.
.
whileloopthatgeneratesoutputeventhoughtheconditionisnotmet:vari:int=5;do{trace(i);i++;}while(i3.
0:methodsandfunctionclosures.
Whetherafunctionisacalledamethodorafunctionclosuredependsonthecontextinwhichthefunctionisdefined.
Afunctioniscalledamethodifyoudefineitaspartofaclassdefinitionorattachittoaninstanceofanobject.
Afunctioniscalledafunctionclosureifitisdefinedinanyotherway.
FunctionshavealwaysbeenextremelyimportantinActionScript.
InActionScript1.
0,forexample,theclasskeyworddidnotexist,so"classes"weredefinedbyconstructorfunctions.
Althoughtheclasskeywordhassincebeenaddedtothelanguage,asolidunderstandingoffunctionsisstillimportantifyouwanttotakefulladvantageofwhatthelanguagehastooffer.
ThiscanbeachallengeforprogrammerswhoexpectActionScriptfunctionstobehavesimilarlytofunctionsinlanguagessuchasC++orJava.
Althoughbasicfunctiondefinitionandinvocationshouldnotpresentachallengetoexperiencedprogrammers,someofthemoreadvancedfeaturesofActionScriptfunctionsrequiresomeexplanation.
BasicfunctionconceptsCallingfunctionsYoucallafunctionbyusingitsidentifierfollowedbytheparenthesesoperator(()).
Youusetheparenthesesoperatortoencloseanyfunctionparametersyouwanttosendtothefunction.
Forexample,thetrace()functionisatop-levelfunctioninActionScript3.
0:trace("Usetracetohelpdebugyourscript");Ifyouarecallingafunctionwithnoparameters,youmustuseanemptypairofparentheses.
Forexample,youcanusetheMath.
random()method,whichtakesnoparameters,togeneratearandomnumber:varrandomNum:Number=Math.
random();75LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011DefiningyourownfunctionsTherearetwowaystodefineafunctioninActionScript3.
0:youcanuseafunctionstatementorafunctionexpression.
Thetechniqueyouchoosedependsonwhetheryoupreferamorestaticordynamicprogrammingstyle.
Defineyourfunctionswithfunctionstatementsifyoupreferstatic,orstrictmode,programming.
Defineyourfunctionswithfunctionexpressionsifyouhaveaspecificneedtodoso.
Functionexpressionsaremoreoftenusedindynamic,orstandardmode,programming.
FunctionstatementsFunctionstatementsarethepreferredtechniquefordefiningfunctionsinstrictmode.
Afunctionstatementbeginswiththefunctionkeyword,followedby:ThefunctionnameTheparameters,inacomma-delimitedlistenclosedinparenthesesThefunctionbody—thatis,theActionScriptcodetobeexecutedwhenthefunctioniscalled,enclosedincurlybracketsForexample,thefollowingcodecreatesafunctionthatdefinesaparameterandthencallsthefunctionusingthestring"hello"astheparametervalue:functiontraceParameter(aParam:String){trace(aParam);}traceParameter("hello");//helloFunctionexpressionsThesecondwaytodeclareafunctionistouseanassignmentstatementwithafunctionexpression,whichisalsosometimescalledafunctionliteralorananonymousfunction.
ThisisamoreverbosemethodthatiswidelyusedinearlierversionsofActionScript.
Anassignmentstatementwithafunctionexpressionbeginswiththevarkeyword,followedby:ThefunctionnameThecolonoperator(:)TheFunctionclasstoindicatethedatatypeTheassignmentoperator(=)ThefunctionkeywordTheparameters,inacomma-delimitedlistenclosedinparenthesesThefunctionbody—thatis,theActionScriptcodetobeexecutedwhenthefunctioniscalled,enclosedincurlybracketsForexample,thefollowingcodedeclaresthetraceParameterfunctionusingafunctionexpression:vartraceParameter:Function=function(aParam:String){trace(aParam);};traceParameter("hello");//hello76LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Noticethatyoudonotspecifyafunctionname,asyoudoinafunctionstatement.
Anotherimportantdifferencebetweenfunctionexpressionsandfunctionstatementsisthatafunctionexpressionisanexpressionratherthanastatement.
Thismeansthatafunctionexpressioncannotstandonitsownasafunctionstatementcan.
Afunctionexpressioncanbeusedonlyasapartofastatement,usuallyanassignmentstatement.
Thefollowingexampleshowsafunctionexpressionassignedtoanarrayelement:vartraceArray:Array=newArray();traceArray[0]=function(aParam:String){trace(aParam);};traceArray[0]("hello");ChoosingbetweenstatementsandexpressionsAsageneralrule,useafunctionstatementunlessspecificcircumstancescallfortheuseofanexpression.
Functionstatementsarelessverbose,andtheyprovideamoreconsistentexperiencebetweenstrictmodeandstandardmodethanfunctionexpressions.
Functionstatementsareeasiertoreadthanassignmentstatementsthatcontainfunctionexpressions.
Functionstatementsmakeyourcodemoreconcise;theyarelessconfusingthanfunctionexpressions,whichrequireyoutouseboththevarandfunctionkeywords.
Functionstatementsprovideamoreconsistentexperiencebetweenthetwocompilermodesinthatyoucanusedotsyntaxinbothstrictandstandardmodetocallamethoddeclaredusingafunctionstatement.
Thisisnotnecessarilytrueformethodsdeclaredwithafunctionexpression.
Forexample,thefollowingcodedefinesaclassnamedExamplewithtwomethods:methodExpression(),whichisdeclaredwithafunctionexpression,andmethodStatement(),whichisdeclaredwithafunctionstatement.
Instrictmode,youcannotusedotsyntaxtocallthemethodExpression()method.
classExample{varmethodExpression=function(){}functionmethodStatement(){}}varmyEx:Example=newExample();myEx.
methodExpression();//errorinstrictmode;okayinstandardmodemyEx.
methodStatement();//okayinstrictandstandardmodesFunctionexpressionsareconsideredbettersuitedtoprogrammingthatfocusesonrun-time,ordynamic,behavior.
Ifyouprefertousestrictmode,butalsoneedtocallamethoddeclaredwithafunctionexpression,youcanuseeitheroftwotechniques.
First,youcancallthemethodusingsquarebrackets([])insteadofthedot(.
)operator.
Thefollowingmethodcallsucceedsinbothstrictmodeandstandardmode:myExample["methodLiteral"]();Second,youcandeclaretheentireclassasadynamicclass.
Althoughthisallowsyoutocallthemethodusingthedotoperator,thedownsideisthatyousacrificesomestrictmodefunctionalityforallinstancesofthatclass.
Forexample,thecompilerdoesnotgenerateanerrorifyouattempttoaccessanundefinedpropertyonaninstanceofadynamicclass.
Therearesomecircumstancesinwhichfunctionexpressionsareuseful.
Onecommonuseoffunctionexpressionsisforfunctionsthatareusedonlyonceandthendiscarded.
Anotherlesscommonuseisforattachingafunctiontoaprototypeproperty.
Formoreinformation,seeTheprototypeobject.
77LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Therearetwosubtledifferencesbetweenfunctionstatementsandfunctionexpressionsthatyoushouldtakeintoaccountwhenchoosingwhichtechniquetouse.
Thefirstdifferenceisthatfunctionexpressionsdonotexistindependentlyasobjectswithregardtomemorymanagementandgarbagecollection.
Inotherwords,whenyouassignafunctionexpressiontoanotherobject,suchasanarrayelementoranobjectproperty,youcreatetheonlyreferencetothatfunctionexpressioninyourcode.
Ifthearrayorobjecttowhichyourfunctionexpressionisattachedgoesoutofscopeorisotherwisenolongeravailable,younolongerhaveaccesstothefunctionexpression.
Ifthearrayorobjectisdeleted,thememorythatthefunctionexpressionusesbecomeseligibleforgarbagecollection,whichmeansthatthememoryiseligibletobereclaimedandreusedforotherpurposes.
Thefollowingexampleshowsthatforafunctionexpression,oncethepropertytowhichtheexpressionisassignedisdeleted,thefunctionisnolongeravailable.
TheclassTestisdynamic,whichmeansthatyoucanaddapropertynamedfunctionExpthatholdsafunctionexpression.
ThefunctionExp()functioncanbecalledwiththedotoperator,butoncethefunctionExppropertyisdeleted,thefunctionisnolongeraccessible.
dynamicclassTest{}varmyTest:Test=newTest();//functionexpressionmyTest.
functionExp=function(){trace("Functionexpression")};myTest.
functionExp();//FunctionexpressiondeletemyTest.
functionExp;myTest.
functionExp();//errorIf,ontheotherhand,thefunctionisfirstdefinedwithafunctionstatement,itexistsasitsownobjectandcontinuestoexistevenafteryoudeletethepropertytowhichitisattached.
Thedeleteoperatoronlyworksonpropertiesofobjects,soevenacalltodeletethefunctionstateFunc()itselfdoesnotwork.
dynamicclassTest{}varmyTest:Test=newTest();//functionstatementfunctionstateFunc(){trace("Functionstatement")}myTest.
statement=stateFunc;myTest.
statement();//FunctionstatementdeletemyTest.
statement;deletestateFunc;//noeffectstateFunc();//FunctionstatementmyTest.
statement();//errorTheseconddifferencebetweenfunctionstatementsandfunctionexpressionsisthatfunctionstatementsexistthroughoutthescopeinwhichtheyaredefined,includinginstatementsthatappearbeforethefunctionstatement.
Functionexpressions,bycontrast,aredefinedonlyforsubsequentstatements.
Forexample,thefollowingcodesuccessfullycallsthescopeTest()functionbeforeitisdefined:statementTest();//statementTestfunctionstatementTest():void{trace("statementTest");}Functionexpressionsarenotavailablebeforetheyaredefined,sothefollowingcoderesultsinarun-timeerror:78LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011expressionTest();//run-timeerrorvarexpressionTest:Function=function(){trace("expressionTest");}ReturningvaluesfromfunctionsToreturnavaluefromyourfunction,usethereturnstatementfollowedbytheexpressionorliteralvaluethatyouwanttoreturn.
Forexample,thefollowingcodereturnsanexpressionrepresentingtheparameter:functiondoubleNum(baseNum:int):int{return(baseNum*2);}Noticethatthereturnstatementterminatesthefunction,sothatanystatementsbelowareturnstatementarenotexecuted,asfollows:functiondoubleNum(baseNum:int):int{return(baseNum*2);trace("afterreturn");//Thistracestatementwillnotbeexecuted.
}Instrictmode,youmustreturnavalueoftheappropriatetypeifyouchoosetospecifyareturntype.
Forexample,thefollowingcodegeneratesanerrorinstrictmode,becauseitdoesnotreturnavalidvalue:functiondoubleNum(baseNum:int):int{trace("afterreturn");}NestedfunctionsYoucannestfunctions,whichmeansthatfunctionscanbedeclaredwithinotherfunctions.
Anestedfunctionisavailableonlywithinitsparentfunctionunlessareferencetothefunctionispassedtoexternalcode.
Forexample,thefollowingcodedeclarestwonestedfunctionsinsidethegetNameAndVersion()function:functiongetNameAndVersion():String{functiongetVersion():String{return"10";}functiongetProductName():String{return"FlashPlayer";}return(getProductName(getVersion());}trace(getNameAndVersion());//FlashPlayer10Whennestedfunctionsarepassedtoexternalcode,theyarepassedasfunctionclosures,whichmeansthatthefunctionretainsanydefinitionsthatareinscopewhenthefunctionisdefined.
Formoreinformation,seeFunctionscope.
79LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011FunctionparametersActionScript3.
0providessomefunctionalityforfunctionparametersthatmayseemnovelforprogrammersnewtothelanguage.
Althoughtheideaofpassingparametersbyvalueorreferenceshouldbefamiliartomostprogrammers,theargumentsobjectandthe.
.
.
(rest)parametermaybenewtomanyofyou.
PassingargumentsbyvalueorbyreferenceInmanyprogramminglanguages,it'simportanttounderstandthedistinctionbetweenpassingargumentsbyvalueorbyreference;thedistinctioncanaffectthewaycodeisdesigned.
Tobepassedbyvaluemeansthatthevalueoftheargumentiscopiedintoalocalvariableforusewithinthefunction.
Tobepassedbyreferencemeansthatonlyareferencetotheargumentispassedinsteadoftheactualvalue.
Nocopyoftheactualargumentismade.
Instead,areferencetothevariablepassedasanargumentiscreatedandassignedtoalocalvariableforusewithinthefunction.
Asareferencetoavariableoutsidethefunction,thelocalvariablegivesyoutheabilitytochangethevalueoftheoriginalvariable.
InActionScript3.
0,allargumentsarepassedbyreference,becauseallvaluesarestoredasobjects.
However,objectsthatbelongtotheprimitivedatatypes,whichincludesBoolean,Number,int,uint,andString,havespecialoperatorsthatmakethembehaveasiftheywerepassedbyvalue.
Forexample,thefollowingcodecreatesafunctionnamedpassPrimitives()thatdefinestwoparametersnamedxParamandyParam,bothoftypeint.
TheseparametersaresimilartolocalvariablesdeclaredinsidethebodyofthepassPrimitives()function.
WhenthefunctioniscalledwiththeargumentsxValueandyValue,theparametersxParamandyParamareinitializedwithreferencestotheintobjectsrepresentedbyxValueandyValue.
Becausetheargumentsareprimitives,theybehaveasifpassedbyvalue.
AlthoughxParamandyParaminitiallycontainonlyreferencestothexValueandyValueobjects,anychangestothevariableswithinthefunctionbodygeneratenewcopiesofthevaluesinmemory.
functionpassPrimitives(xParam:int,yParam:int):void{xParam++;yParam++;trace(xParam,yParam);}varxValue:int=10;varyValue:int=15;trace(xValue,yValue);//1015passPrimitives(xValue,yValue);//1116trace(xValue,yValue);//1015WithinthepassPrimitives()function,thevaluesofxParamandyParamareincremented,butthisdoesnotaffectthevaluesofxValueandyValue,asshowninthelasttracestatement.
Thiswouldbetrueeveniftheparameterswerenamedidenticallytothevariables,xValueandyValue,becausethexValueandyValueinsidethefunctionwouldpointtonewlocationsinmemorythatexistseparatelyfromthevariablesofthesamenameoutsidethefunction.
Allotherobjects—thatis,objectsthatdonotbelongtotheprimitivedatatypes—arealwayspassedbyreference,whichgivesyouabilitytochangethevalueoftheoriginalvariable.
Forexample,thefollowingcodecreatesanobjectnamedobjVarwithtwoproperties,xandy.
TheobjectispassedasanargumenttothepassByRef()function.
Becausetheobjectisnotaprimitivetype,theobjectisnotonlypassedbyreference,butalsostaysareference.
Thismeansthatchangesmadetotheparameterswithinthefunctionaffecttheobjectpropertiesoutsidethefunction.
80LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011functionpassByRef(objParam:Object):void{objParam.
x++;objParam.
y++;trace(objParam.
x,objParam.
y);}varobjVar:Object={x:10,y:15};trace(objVar.
x,objVar.
y);//1015passByRef(objVar);//1116trace(objVar.
x,objVar.
y);//1116TheobjParamparameterreferencesthesameobjectastheglobalobjVarvariable.
Asyoucanseefromthetracestatementsintheexample,changestothexandypropertiesoftheobjParamobjectarereflectedintheobjVarobject.
DefaultparametervaluesInActionScript3.
0,youcandeclaredefaultparametervaluesforafunction.
Ifacalltoafunctionwithdefaultparametervaluesomitsaparameterwithdefaultvalues,thevaluespecifiedinthefunctiondefinitionforthatparameterisused.
Allparameterswithdefaultvaluesmustbeplacedattheendoftheparameterlist.
Thevaluesassignedasdefaultvaluesmustbecompile-timeconstants.
Theexistenceofadefaultvalueforaparametereffectivelymakesthatparameteranoptionalparameter.
Aparameterwithoutadefaultvalueisconsideredarequiredparameter.
Forexample,thefollowingcodecreatesafunctionwiththreeparameters,twoofwhichhavedefaultvalues.
Whenthefunctioniscalledwithonlyoneparameter,thedefaultvaluesfortheparametersareused.
functiondefaultValues(x:int,y:int=3,z:int=5):void{trace(x,y,z);}defaultValues(1);//135TheargumentsobjectWhenparametersarepassedtoafunction,youcanusetheargumentsobjecttoaccessinformationabouttheparameterspassedtoyourfunction.
Someimportantaspectsoftheargumentsobjectincludethefollowing:Theargumentsobjectisanarraythatincludesalltheparameterspassedtothefunction.
Thearguments.
lengthpropertyreportsthenumberofparameterspassedtothefunction.
Thearguments.
calleepropertyprovidesareferencetothefunctionitself,whichisusefulforrecursivecallstofunctionexpressions.
Note:Theargumentsobjectisnotavailableifanyparameterisnamedargumentsorifyouusethe.
.
.
(rest)parameter.
Iftheargumentsobjectisreferencedinthebodyofafunction,ActionScript3.
0allowsfunctioncallstoincludemoreparametersthanthosedefinedinthefunctiondefinition,butgeneratesacompilererrorinstrictmodeifthenumberofparametersdoesn'tmatchthenumberofrequiredparameters(andoptionally,anyoptionalparameters).
Youcanusethearrayaspectoftheargumentsobjecttoaccessanyparameterpassedtothefunction,whetherornotthatparameterisdefinedinthefunctiondefinition.
Thefollowingexample,whichonlycompilesinstandardmode,usestheargumentsarrayalongwiththearguments.
lengthpropertytotracealltheparameterspassedtothetraceArgArray()function:81LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011functiontraceArgArray(x:int):void{for(vari:uint=0;i3);//output://1//2//3Thearguments.
calleepropertyisoftenusedinanonymousfunctionstocreaterecursion.
Youcanuseittoaddflexibilitytoyourcode.
Ifthenameofarecursivefunctionchangesoverthecourseofyourdevelopmentcycle,youneednotworryaboutchangingtherecursivecallinyourfunctionbodyifyouusearguments.
calleeinsteadofthefunctionname.
Thearguments.
calleepropertyisusedinthefollowingfunctionexpressiontoenablerecursion:varfactorial:Function=function(x:uint){if(x==0){return1;}else{return(x*arguments.
callee(x-1));}}trace(factorial(5));//120Ifyouusethe.
.
.
(rest)parameterinyourfunctiondeclaration,theargumentsobjectisnotavailabletoyou.
Instead,youmustaccesstheparametersusingtheparameternamesthatyoudeclaredforthem.
Youshouldalsobecarefultoavoidusingthestring"arguments"asaparametername,becauseitshadowstheargumentsobject.
Forexample,ifthefunctiontraceArgArray()isrewrittensothatanargumentsparameterisadded,thereferencestoargumentsinthefunctionbodyrefertotheparameterratherthantheargumentsobject.
Thefollowingcodeproducesnooutput:functiontraceArgArray(x:int,arguments:int):void{for(vari:uint=0;i3);//nooutput82LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011TheargumentsobjectinpreviousversionsofActionScriptalsocontainedapropertynamedcaller,whichisareferencetothefunctionthatcalledthecurrentfunction.
ThecallerpropertyisnotpresentinActionScript3.
0,butifyouneedareferencetothecallingfunction,youcanalterthecallingfunctionsothatitpassesanextraparameterthatisareferencetoitself.
The.
.
.
(rest)parameterActionScript3.
0introducesanewparameterdeclarationcalledthe.
.
.
(rest)parameter.
Thisparameterallowsyoutospecifyanarrayparameterthatacceptsanynumberofcomma-delimitedarguments.
Theparametercanhaveanynamethatisnotareservedword.
Thisparameterdeclarationmustbethelastparameterspecified.
Useofthisparametermakestheargumentsobjectunavailable.
Althoughthe.
.
.
(rest)parametergivesyouthesamefunctionalityastheargumentsarrayandarguments.
lengthproperty,itdoesnotprovidefunctionalitysimilartothatprovidedbyarguments.
callee.
Youshouldensurethatyoudonotneedtousearguments.
calleebeforeusingthe.
.
.
(rest)parameter.
ThefollowingexamplerewritesthetraceArgArray()functionusingthe.
.
.
(rest)parameterinsteadoftheargumentsobject:functiontraceArgArray(.
.
.
args):void{for(vari:uint=0;i3);//output://1//2//3The.
.
.
(rest)parametercanalsobeusedwithotherparameters,aslongasitisthelastparameterlisted.
ThefollowingexamplemodifiesthetraceArgArray()functionsothatitsfirstparameter,x,isoftypeint,andthesecondparameterusesthe.
.
.
(rest)parameter.
Theoutputskipsthefirstvalue,becausethefirstparameterisnolongerpartofthearraycreatedbythe.
.
.
(rest)parameter.
functiontraceArgArray(x:int,.
.
.
args){for(vari:uint=0;i3);//output://2//3FunctionsasobjectsFunctionsinActionScript3.
0areobjects.
Whenyoucreateafunction,youarecreatinganobjectthatnotonlycanbepassedasaparametertoanotherfunction,butalsocanhavepropertiesandmethodsattachedtoit.
83LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011Functionspassedasargumentstoanotherfunctionarepassedbyreferenceandnotbyvalue.
Whenyoupassafunctionasanargument,youuseonlytheidentifierandnottheparenthesesoperatorthatyouusetocallthemethod.
Forexample,thefollowingcodepassesafunctionnamedclickListener()asanargumenttotheaddEventListener()method:addEventListener(MouseEvent.
CLICK,clickListener);AlthoughitmayseemstrangetoprogrammersnewtoActionScript,functionscanhavepropertiesandmethods,justasanyotherobjectcan.
Infact,everyfunctionhasaread-onlypropertynamedlengththatstoresthenumberofparametersdefinedforthefunction.
Thisisdifferentfromthearguments.
lengthproperty,whichreportsthenumberofargumentssenttothefunction.
RecallthatinActionScript,thenumberofargumentssenttoafunctioncanexceedthenumberofparametersdefinedforthatfunction.
Thefollowingexample,whichcompilesonlyinstandardmodebecausestrictmoderequiresanexactmatchbetweenthenumberofargumentspassedandthenumberofparametersdefined,showsthedifferencebetweenthetwoproperties://CompilesonlyinstandardmodefunctiontraceLength(x:uint,y:uint):void{trace("argumentsreceived:"+arguments.
length);trace("argumentsexpected:"+traceLength.
length);}traceLength(3,5,7,11);/*output:argumentsreceived:4argumentsexpected:2*/Instandardmode,youcandefineyourownfunctionpropertiesbydefiningthemoutsideyourfunctionbody.
Functionpropertiescanserveasquasi-staticpropertiesthatallowyoutosavethestateofavariablerelatedtothefunction.
Forexample,youmaywanttotrackthenumberoftimesaparticularfunctioniscalled.
Suchfunctionalitycouldbeusefulifyouarewritingagameandwanttotrackthenumberoftimesauserusesaspecificcommand,althoughyoucouldalsouseastaticclasspropertyforthis.
Thefollowingexample,whichcompilesonlyinstandardmodebecausestrictmodedoesnotallowyoutoadddynamicpropertiestofunctions,createsafunctionpropertyoutsidethefunctiondeclarationandincrementsthepropertyeachtimethefunctioniscalled://CompilesonlyinstandardmodevarsomeFunction:Function=function():void{someFunction.
counter++;}someFunction.
counter=0;someFunction();someFunction();trace(someFunction.
counter);//2FunctionscopeAfunction'sscopedeterminesnotonlywhereinaprogramthatfunctioncanbecalled,butalsowhatdefinitionsthefunctioncanaccess.
Thesamescoperulesthatapplytovariableidentifiersapplytofunctionidentifiers.
Afunctiondeclaredintheglobalscopeisavailablethroughoutyourcode.
Forexample,ActionScript3.
0containsglobalfunctions,suchasisNaN()andparseInt(),thatareavailableanywhereinyourcode.
Anestedfunction—afunctiondeclaredwithinanotherfunction—canbeusedanywhereinthefunctioninwhichitwasdeclared.
84LEARNINGACTIONSCRIPT3.
0ActionScriptlanguageandsyntaxLastupdated5/2/2011ThescopechainAnytimeafunctionbeginsexecution,anumberofobjectsandpropertiesarecreated.
First,aspecialobjectcalledanactivationobjectiscreatedthatstorestheparametersandanylocalvariablesorfunctionsdeclaredinthefunctionbody.
Youcannotaccesstheactivationobjectdirectly,becauseitisaninternalmechanism.
Second,ascopechainiscreatedthatcontainsanorderedlistofobjectsthattheruntimechecksforidentifierdeclarations.
Everyfunctionthatexecuteshasascopechainthatisstoredinaninternalproperty.
Foranestedfunction,thescopechainstartswithitsownactivationobject,followedbyitsparentfunction'sactivationobject.
Thechaincontinuesinthismanneruntilitreachestheglobalobject.
TheglobalobjectiscreatedwhenanActionScriptprogrambegins,andcontainsallglobalvariablesandfunctions.
FunctionclosuresAfunctionclosureisanobjectthatcontainsasnapshotofafunctionanditslexicalenvironment.
Afunction'slexicalenvironmentincludesallthevariables,properties,methods,andobjectsinthefunction'sscopechain,alongwiththeirvalues.
Functionclosuresarecreatedanytimeafunctionisexecutedapartfromanobjectoraclass.
Thefactthatfunctionclosuresretainthescopeinwhichtheyweredefinedcreatesinterestingresultswhenafunctionispassedasanargumentorareturnvalueintoadifferentscope.
Forexample,thefollowingcodecreatestwofunctions:foo(),whichreturnsanestedfunctionnamedrectArea()thatcalculatestheareaofarectangle,andbar(),whichcallsfoo()andstoresthereturnedfunctionclosureinavariablenamedmyProduct.
Eventhoughthebar()functiondefinesitsownlocalvariablex(withavalueof2),whenthefunctionclosuremyProduct()iscalled,itretainsthevariablex(withavalueof40)definedinfunctionfoo().
Thebar()functionthereforereturnsthevalue160insteadof8.
functionfoo():Function{varx:int=40;functionrectArea(y:int):int//functionclosuredefined{returnx*y}returnrectArea;}functionbar():void{varx:int=2;vary:int=4;varmyProduct:Function=foo();trace(myProduct(4));//functionclosurecalled}bar();//160Methodsbehavesimilarlyinthattheyalsoretaininformationaboutthelexicalenvironmentinwhichtheywerecreated.
Thischaracteristicismostnoticeablewhenamethodisextractedfromitsinstance,whichcreatesaboundmethod.
Themaindifferencebetweenafunctionclosureandaboundmethodisthatthevalueofthethiskeywordinaboundmethodalwaysreferstotheinstancetowhichitwasoriginallyattached,whereasinafunctionclosurethevalueofthethiskeywordcanchange.
85Lastupdated5/2/2011Chapter4:Object-orientedprogramminginActionScriptIntroductiontoobject-orientedprogrammingObject-orientedprogramming(OOP)isawayoforganizingthecodeinaprogrambygroupingitintoobjects.
Thetermobjectinthissensemeansanindividualelementthatincludeinformation(datavalues)andfunctionality.
Whenyouuseanobject-orientedapproachtoorganizingaprogramyougroupparticularpiecesofinformationtogetherwithcommonfunctionalityoractionsassociatedwiththatinformation.
Forexample,youcouldgroupmusicinformationlikealbumtitle,tracktitle,orartistnamewithfunctionalitysuchas"addtracktoplaylist"or"playallsongsbythisartist".
Thesepiecesarecombinedintoasingleitem,anobject(forexample,an"Album"or"MusicTrack").
Bundlingvaluesandfunctionstogetherprovidesseveralbenefits.
Onekeybenefitisthatyouonlyneedingtouseasinglevariableratherthanmultipleones.
Inaddition,itkeepsrelatedfunctionalitytogether.
Finally,combininginformationandfunctionalityallowsyoutostructureprogramsinwaysthatmorecloselymatchtherealworld.
ClassesAclassisanabstractrepresentationofanobject.
Aclassstoresinformationaboutthetypesofdatathatanobjectcanholdandthebehaviorsthatanobjectcanexhibit.
Theusefulnessofsuchanabstractionisnotnecessarilyapparentwhenyouwritesmallscriptsthatcontainonlyafewobjectsinteractingwithoneanother.
However,asthescopeofaprogramgrowsthenumberofobjectsthatmustbemanagedincreases.
Inthatcaseclassesallowyoutobettercontrolhowobjectsarecreatedandhowtheyinteractwithoneanother.
AsfarbackasActionScript1.
0,ActionScriptprogrammerscoulduseFunctionobjectstocreateconstructsthatresembledclasses.
ActionScript2.
0addedformalsupportforclasseswithkeywordssuchasclassandextends.
ActionScript3.
0notonlycontinuestosupportthekeywordsintroducedinActionScript2.
0.
Italsoaddsnewcapabilities.
Forexample,ActionScript3.
0includesenhancedaccesscontrolwiththeprotectedandinternalattributes.
Italsoprovidesbettercontroloverinheritancewiththefinalandoverridekeywords.
FordeveloperswhohavecreatedclassesinprogramminglanguageslikeJava,C++,orC#,ActionScriptprovidesafamiliarexperience.
ActionScriptsharesmanyofthesamekeywordsandattributenames,suchasclass,extends,andpublic.
Note:IntheAdobeActionScriptdocumentation,thetermpropertymeansanymemberofanobjectorclass,includingvariables,constants,andmethods.
Inaddition,althoughthetermsclassandstaticareoftenusedinterchangeably,herethesetermsaredistinct.
Forexample,thephrase"classproperties"isusedtomeanallthemembersofaclass,ratherthanonlythestaticmembers.
ClassdefinitionsActionScript3.
0classdefinitionsusesyntaxthatissimilartothesyntaxusedinActionScript2.
0classdefinitions.
Propersyntaxforaclassdefinitioncallsfortheclasskeywordfollowedbytheclassname.
Theclassbody,enclosedbycurlybrackets({}),followstheclassname.
Forexample,thefollowingcodecreatesaclassnamedShapethatcontainsonevariable,namedvisible:86LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011publicclassShape{varvisible:Boolean=true;}Onesignificantsyntaxchangeinvolvesclassdefinitionsthatareinsideapackage.
InActionScript2.
0,ifaclassisinsideapackage,thepackagenamemustbeincludedintheclassdeclaration.
InActionScript3.
0,whichintroducesthepackagestatement,thepackagenamemustbeincludedinthepackagedeclarationinsteadofintheclassdeclaration.
Forexample,thefollowingclassdeclarationsshowhowtheBitmapDataclass,whichispartoftheflash.
displaypackage,isdefinedinActionScript2.
0andActionScript3.
0://ActionScript2.
0classflash.
display.
BitmapData{}//ActionScript3.
0packageflash.
display{publicclassBitmapData{}}ClassattributesActionScript3.
0allowsyoutomodifyclassdefinitionsusingoneofthefollowingfourattributes:Foreachoftheseattributes,exceptforinternal,youexplicitlyincludetheattributetogettheassociatedbehavior.
Forexample,ifyoudonotincludethedynamicattributewhendefiningaclass,youcan'taddpropertiestoaclassinstanceatruntime.
Youexplicitlyassignanattributebyplacingitatthebeginningoftheclassdefinition,asthefollowingcodedemonstrates:dynamicclassShape{}Noticethatthelistdoesnotincludeanattributenamedabstract.
AbstractclassesarenotsupportedinActionScript3.
0.
Noticealsothatthelistdoesnotincludeattributesnamedprivateandprotected.
Theseattributeshavemeaningonlyinsideaclassdefinition,andcannotbeappliedtoclassesthemselves.
Ifyoudonotwantaclasstobepubliclyvisibleoutsideapackage,placetheclassinsideapackageandmarktheclasswiththeinternalattribute.
Alternatively,youcanomitboththeinternalandpublicattributes,andthecompilerautomaticallyaddstheinternalattributeforyou.
Youcanalsodefineaclasstoonlybevisibleinsidethesourcefileinwhichitisdefined.
Placetheclassatthebottomofyoursourcefile,belowtheclosingcurlybracketofthepackagedefinition.
ClassbodyTheclassbodyisenclosedbycurlybrackets.
Itdefinesthevariables,constants,andmethodsofyourclass.
ThefollowingexampleshowsthedeclarationfortheAccessibilityclassinActionScript3.
0:publicfinalclassAccessibility{publicstaticfunctiongetactive():Boolean;publicstaticfunctionupdateProperties():void;}AttributeDefinitiondynamicAllowpropertiestobeaddedtoinstancesatruntime.
finalMustnotbeextendedbyanotherclass.
internal(default)Visibletoreferencesinsidethecurrentpackage.
publicVisibletoreferenceseverywhere.
87LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Youcanalsodefineanamespaceinsideaclassbody.
Thefollowingexampleshowshowanamespacecanbedefinedwithinaclassbodyandusedasanattributeofamethodinthatclass:publicclassSampleClass{publicnamespacesampleNamespace;sampleNamespacefunctiondoSomething():void;}ActionScript3.
0allowsyoutoincludenotonlydefinitionsinaclassbody,butalsostatements.
Statementsthatareinsideaclassbody,butoutsideamethoddefinition,areexecutedexactlyonce.
Thisexecutionhappenswhentheclassdefinitionisfirstencounteredandtheassociatedclassobjectiscreated.
Thefollowingexampleincludesacalltoanexternalfunction,hello(),andatracestatementthatoutputsaconfirmationmessagewhentheclassisdefined:functionhello():String{trace("hola");}classSampleClass{hello();trace("classcreated");}//outputwhenclassiscreatedholaclasscreatedInActionScript3.
0itispermissibletodefineastaticpropertyandaninstancepropertywiththesamenameinthesameclassbody.
Forexample,thefollowingcodedeclaresastaticvariablenamedmessageandaninstancevariableofthesamename:classStaticTest{staticvarmessage:String="staticvariable";varmessage:String="instancevariable";}//InyourscriptvarmyST:StaticTest=newStaticTest();trace(StaticTest.
message);//output:staticvariabletrace(myST.
message);//output:instancevariableClasspropertyattributesIndiscussionsoftheActionScriptobjectmodel,thetermpropertymeansanythingthatcanbeamemberofaclass,includingvariables,constants,andmethods.
However,intheAdobeActionScript3.
0ReferencefortheAdobeFlashPlatformthetermisusedmorenarrowly.
Inthatcontextthetermpropertyincludesonlyclassmembersthatarevariablesoraredefinedbyagetterorsettermethod.
InActionScript3.
0,thereisasetofattributesthatcanbeusedwithanypropertyofaclass.
Thefollowingtableliststhissetofattributes.
AttributeDefinitioninternal(default)Visibletoreferencesinsidethesamepackage.
privateVisibletoreferencesinthesameclass.
protectedVisibletoreferencesinthesameclassandderivedclasses.
88LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011AccesscontrolnamespaceattributesActionScript3.
0providesfourspecialattributesthatcontrolaccesstopropertiesdefinedinsideaclass:public,private,protected,andinternal.
Thepublicattributemakesapropertyvisibleanywhereinyourscript.
Forexample,tomakeamethodavailabletocodeoutsideitspackage,youmustdeclarethemethodwiththepublicattribute.
Thisistrueforanyproperty,whetheritisdeclaredusingthevar,const,orfunctionkeywords.
Theprivateattributemakesapropertyvisibleonlytocallerswithintheproperty'sdefiningclass.
ThisbehaviordiffersfromthatoftheprivateattributeinActionScript2.
0,whichallowedasubclasstoaccessaprivatepropertyinasuperclass.
Anothersignificantchangeinbehaviorhastodowithrun-timeaccess.
InActionScript2.
0,theprivatekeywordprohibitedaccessonlyatcompiletimeandwaseasilycircumventedatruntime.
InActionScript3.
0,thisisnolongertrue.
Propertiesthataremarkedasprivateareunavailableatbothcompiletimeandruntime.
Forexample,thefollowingcodecreatesasimpleclassnamedPrivateExamplewithoneprivatevariable,andthenattemptstoaccesstheprivatevariablefromoutsidetheclass.
classPrivateExample{privatevarprivVar:String="privatevariable";}varmyExample:PrivateExample=newPrivateExample();trace(myExample.
privVar);//compile-timeerrorinstrictmodetrace(myExample["privVar"]);//ActionScript2.
0allowsaccess,butinActionScript3.
0,thisisarun-timeerror.
InActionScript3.
0,anattempttoaccessaprivatepropertyusingthedotoperator(myExample.
privVar)resultsinacompile-timeerrorifyouareusingstrictmode.
Otherwise,theerrorisreportedatruntime,justasitiswhenyouusethepropertyaccessoperator(myExample["privVar"]).
Thefollowingtablesummarizestheresultsofattemptingtoaccessaprivatepropertythatbelongstoasealed(notdynamic)class:Inclassesdeclaredwiththedynamicattribute,attemptstoaccessaprivatevariabledonotresultinarun-timeerror.
Instead,thevariableisnotvisible,sothevalueundefinedisreturned.
Acompile-timeerroroccurs,however,ifyouusethedotoperatorinstrictmode.
Thefollowingexampleisthesameasthepreviousexample,exceptthatthePrivateExampleclassisdeclaredasadynamicclass:publicVisibletoreferenceseverywhere.
staticSpecifiesthatapropertybelongstotheclass,asopposedtoinstancesoftheclass.
UserDefinedNamespaceCustomnamespacenamedefinedbyuser.
StrictmodeStandardmodedotoperator(.
)compile-timeerrorrun-timeerrorbracketoperator([])run-timeerrorrun-timeerrorAttributeDefinition89LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011dynamicclassPrivateExample{privatevarprivVar:String="privatevariable";}varmyExample:PrivateExample=newPrivateExample();trace(myExample.
privVar);//compile-timeerrorinstrictmodetrace(myExample["privVar"]);//output:undefinedDynamicclassesgenerallyreturnthevalueundefinedinsteadofgeneratinganerrorwhencodeexternaltoaclassattemptstoaccessaprivateproperty.
Thefollowingtableshowsthatanerrorisgeneratedonlywhenthedotoperatorisusedtoaccessaprivatepropertyinstrictmode:Theprotectedattribute,whichisnewforActionScript3.
0,makesapropertyvisibletocallerswithinitsownclassorinasubclass.
Inotherwords,aprotectedpropertyisavailablewithinitsownclassortoclassesthatlieanywherebelowitintheinheritancehierarchy.
Thisistruewhetherthesubclassisinthesamepackageorinadifferentpackage.
ForthosefamiliarwithActionScript2.
0,thisfunctionalityissimilartotheprivateattributeinActionScript2.
0.
TheActionScript3.
0protectedattributeisalsosimilartotheprotectedattributeinJava.
ItdiffersinthattheJavaversionalsopermitsaccesstocallerswithinthesamepackage.
Theprotectedattributeisusefulwhenyouhaveavariableormethodthatyoursubclassesneedbutthatyouwanttohidefromcodethatisoutsidetheinheritancechain.
Theinternalattribute,whichisnewforActionScript3.
0,makesapropertyvisibletocallerswithinitsownpackage.
Thisisthedefaultattributeforcodeinsideapackage,anditappliestoanypropertythatdoesnothaveanyofthefollowingattributes:publicprivateprotectedauser-definednamespaceTheinternalattributeissimilartothedefaultaccesscontrolinJava,althoughinJavathereisnoexplicitnameforthislevelofaccess,anditcanbeachievedonlythroughtheomissionofanyotheraccessmodifier.
TheinternalattributeisavailableinActionScript3.
0togiveyoutheoptionofexplicitlysignifyingyourintenttomakeapropertyvisibleonlytocallerswithinitsownpackage.
staticattributeThestaticattribute,whichcanbeusedwithpropertiesdeclaredwiththevar,const,orfunctionkeywords,allowsyoutoattachapropertytotheclassratherthantoinstancesoftheclass.
Codeexternaltotheclassmustcallstaticpropertiesbyusingtheclassnameinsteadofaninstancename.
Staticpropertiesarenotinheritedbysubclasses,butthepropertiesarepartofasubclass'sscopechain.
Thismeansthatwithinthebodyofasubclass,astaticvariableormethodcanbeusedwithoutreferencingtheclassinwhichitwasdefined.
StrictmodeStandardmodedotoperator(.
)compile-timeerrorundefinedbracketoperator([])undefinedundefined90LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011User-definednamespaceattributesAsanalternativetothepredefinedaccesscontrolattributes,youcancreateacustomnamespaceforuseasanattribute.
Onlyonenamespaceattributecanbeusedperdefinition,andyoucannotuseanamespaceattributeincombinationwithanyoftheaccesscontrolattributes(public,private,protected,internal).
VariablesVariablescanbedeclaredwitheitherthevarorconstkeywords.
Variablesdeclaredwiththevarkeywordcanhavetheirvalueschangedmultipletimesthroughouttheexecutionofascript.
Variablesdeclaredwiththeconstkeywordarecalledconstants,andcanhavevaluesassignedtothemonlyonce.
Anattempttoassignanewvaluetoaninitializedconstantresultsinanerror.
StaticvariablesStaticvariablesaredeclaredusingacombinationofthestatickeywordandeitherthevarorconststatement.
Staticvariables,whichareattachedtoaclassratherthananinstanceofaclass,areusefulforstoringandsharinginformationthatappliestoanentireclassofobjects.
Forexample,astaticvariableisappropriateifyouwanttokeepatallyofthenumberoftimesaclassisinstantiatedorifyouwanttostorethemaximumnumberofclassinstancesthatareallowed.
ThefollowingexamplecreatesatotalCountvariabletotrackthenumberofclassinstantiationsandaMAX_NUMconstanttostorethemaximumnumberofinstantiations.
ThetotalCountandMAX_NUMvariablesarestatic,becausetheycontainvaluesthatapplytotheclassasawholeratherthantoaparticularinstance.
classStaticVars{publicstaticvartotalCount:int=0;publicstaticconstMAX_NUM:uint=16;}CodethatisexternaltotheStaticVarsclassandanyofitssubclassescanreferencethetotalCountandMAX_NUMpropertiesonlythroughtheclassitself.
Forexample,thefollowingcodeworks:trace(StaticVars.
totalCount);//output:0trace(StaticVars.
MAX_NUM);//output:16Youcannotaccessstaticvariablesthroughaninstanceoftheclass,sothefollowingcodereturnserrors:varmyStaticVars:StaticVars=newStaticVars();trace(myStaticVars.
totalCount);//errortrace(myStaticVars.
MAX_NUM);//errorVariablesthataredeclaredwithboththestaticandconstkeywordsmustbeinitializedatthesametimeasyoudeclaretheconstant,astheStaticVarsclassdoesforMAX_NUM.
YoucannotassignavaluetoMAX_NUMinsidetheconstructororaninstancemethod.
Thefollowingcodegeneratesanerror,becauseitisnotavalidwaytoinitializeastaticconstant://!
!
ErrortoinitializestaticconstantthiswayclassStaticVars2{publicstaticconstUNIQUESORT:uint;functioninitializeStatic():void{UNIQUESORT=16;}}91LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011InstancevariablesInstancevariablesincludepropertiesdeclaredwiththevarandconstkeywords,butwithoutthestatickeyword.
Instancevariables,whichareattachedtoclassinstancesratherthantoanentireclass,areusefulforstoringvaluesthatarespecifictoaninstance.
Forexample,theArrayclasshasaninstancepropertynamedlength,whichstoresthenumberofarrayelementsthataparticularinstanceoftheArrayclassholds.
Instancevariables,whetherdeclaredasvarorconst,cannotbeoverriddeninasubclass.
Youcan,however,achievefunctionalitythatissimilartooverridingvariablesbyoverridinggetterandsettermethods.
MethodsMethodsarefunctionsthatarepartofaclassdefinition.
Onceaninstanceoftheclassiscreated,amethodisboundtothatinstance.
Unlikeafunctiondeclaredoutsideaclass,amethodcannotbeusedapartfromtheinstancetowhichitisattached.
Methodsaredefinedusingthefunctionkeyword.
Aswithanyclassproperty,youcanapplyanyoftheclasspropertyattributestomethods,includingprivate,protected,public,internal,static,oracustomnamespace.
Youcanuseafunctionstatementsuchasthefollowing:publicfunctionsampleFunction():String{}Oryoucanuseavariabletowhichyouassignafunctionexpression,asfollows:publicvarsampleFunction:Function=function(){}Inmostcases,useafunctionstatementinsteadofafunctionexpressionforthefollowingreasons:Functionstatementsaremoreconciseandeasiertoread.
Functionstatementsallowyoutousetheoverrideandfinalkeywords.
Functionstatementscreateastrongerbondbetweentheidentifier(thenameofthefunction)andthecodewithinthemethodbody.
Becausethevalueofavariablecanbechangedwithanassignmentstatement,theconnectionbetweenavariableanditsfunctionexpressioncanbeseveredatanytime.
Althoughyoucanworkaroundthisissuebydeclaringthevariablewithconstinsteadofvar,suchatechniqueisnotconsideredabestpractice.
Itmakesthecodehardtoreadandpreventstheuseoftheoverrideandfinalkeywords.
Onecaseinwhichyoumustuseafunctionexpressioniswhenyouchoosetoattachafunctiontotheprototypeobject.
ConstructormethodsConstructormethods,sometimescalledconstructors,arefunctionsthatsharethesamenameastheclassinwhichtheyaredefined.
Anycodethatyouincludeinaconstructormethodisexecutedwheneveraninstanceoftheclassiscreatedwiththenewkeyword.
Forexample,thefollowingcodedefinesasimpleclassnamedExamplethatcontainsasinglepropertynamedstatus.
Theinitialvalueofthestatusvariableissetinsidetheconstructorfunction.
classExample{publicvarstatus:String;publicfunctionExample(){status="initialized";}}varmyExample:Example=newExample();trace(myExample.
status);//output:initialized92LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Constructormethodscanonlybepublic,buttheuseofthepublicattributeisoptional.
Youcannotuseanyoftheotheraccesscontrolspecifiers,includingprivate,protected,orinternal,onaconstructor.
Youalsocannotuseauser-definednamespacewithaconstructormethod.
Aconstructorcanmakeanexplicitcalltotheconstructorofitsdirectsuperclassbyusingthesuper()statement.
Ifthesuperclassconstructorisnotexplicitlycalled,thecompilerautomaticallyinsertsacallbeforethefirststatementintheconstructorbody.
Youcanalsocallmethodsofthesuperclassbyusingthesuperprefixasareferencetothesuperclass.
Ifyoudecidetousebothsuper()andsuperinthesameconstructorbody,besuretocallsuper()first.
Otherwise,thesuperreferencedoesnotbehaveasexpected.
Thesuper()constructorshouldalsobecalledbeforeanythroworreturnstatement.
Thefollowingexampledemonstrateswhathappensifyouattempttousethesuperreferencebeforecallingthesuper()constructor.
Anewclass,ExampleEx,extendstheExampleclass.
TheExampleExconstructorattemptstoaccessthestatusvariabledefinedinitssuperclass,butdoessobeforecallingsuper().
Thetrace()statementinsidetheExampleExconstructorproducesthevaluenull,becausethestatusvariableisnotavailableuntilthesuper()constructorexecutes.
classExampleExextendsExample{publicfunctionExampleEx(){trace(super.
status);super();}}varmySample:ExampleEx=newExampleEx();//output:nullAlthoughitislegaltousethereturnstatementinsideaconstructor,itisnotpermissibletoreturnavalue.
Inotherwords,returnstatementsmustnothaveassociatedexpressionsorvalues.
Accordingly,constructormethodsarenotallowedtoreturnvalues,whichmeansthatnoreturntypecanbespecified.
Ifyoudonotdefineaconstructormethodinyourclass,thecompilerautomaticallycreatesanemptyconstructorforyou.
Ifyourclassextendsanotherclass,thecompilerincludesasuper()callintheconstructoritgenerates.
StaticmethodsStaticmethods,alsocalledclassmethods,aremethodsthataredeclaredwiththestatickeyword.
Staticmethods,whichareattachedtoaclassratherthantoaninstanceofaclass,areusefulforencapsulatingfunctionalitythataffectssomethingotherthanthestateofanindividualinstance.
Becausestaticmethodsareattachedtoaclassasawhole,staticmethodscanbeaccessedonlythroughaclassandnotthroughaninstanceoftheclass.
Staticmethodsareusefulforencapsulatingfunctionalitythatisnotlimitedtoaffectingthestateofclassinstances.
Inotherwords,amethodshouldbestaticifitprovidesfunctionalitythatdoesnotdirectlyaffectthevalueofaclassinstance.
Forexample,theDateclasshasastaticmethodnamedparse(),whichtakesastringandconvertsittoanumber.
Themethodisstaticbecauseitdoesnotaffectanindividualinstanceoftheclass.
Instead,theparse()methodtakesastringthatrepresentsadatevalue,parsesthestring,andreturnsanumberinaformatcompatiblewiththeinternalrepresentationofaDateobject.
Thismethodisnotaninstancemethod,becauseitdoesnotmakesensetoapplythemethodtoaninstanceoftheDateclass.
Contrastthestaticparse()methodwithoneoftheinstancemethodsoftheDateclass,suchasgetMonth().
ThegetMonth()methodisaninstancemethod,becauseitoperatesdirectlyonthevalueofaninstancebyretrievingaspecificcomponent,themonth,ofaDateinstance.
93LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Becausestaticmethodsarenotboundtoindividualinstances,youcannotusethekeywordsthisorsuperwithinthebodyofastaticmethod.
Boththethisreferenceandthesuperreferencehavemeaningonlywithinthecontextofaninstancemethod.
Incontrastwithsomeotherclass-basedprogramminglanguages,staticmethodsinActionScript3.
0arenotinherited.
InstancemethodsInstancemethodsaremethodsthataredeclaredwithoutthestatickeyword.
Instancemethods,whichareattachedtoinstancesofaclassinsteadoftheclassasawhole,areusefulforimplementingfunctionalitythataffectsindividualinstancesofaclass.
Forexample,theArrayclasscontainsaninstancemethodnamedsort(),whichoperatesdirectlyonArrayinstances.
Withinthebodyofaninstancemethod,bothstaticandinstancevariablesareinscope,whichmeansthatvariablesdefinedinthesameclasscanbereferencedusingasimpleidentifier.
Forexample,thefollowingclass,CustomArray,extendstheArrayclass.
TheCustomArrayclassdefinesastaticvariablenamedarrayCountTotaltotrackthetotalnumberofclassinstances,aninstancevariablenamedarrayNumberthattrackstheorderinwhichtheinstanceswerecreated,andaninstancemethodnamedgetPosition()thatreturnsthevaluesofthesevariables.
publicclassCustomArrayextendsArray{publicstaticvararrayCountTotal:int=0;publicvararrayNumber:int;publicfunctionCustomArray(){arrayNumber=++arrayCountTotal;}publicfunctiongetArrayPosition():String{return("Array"+arrayNumber+"of"+arrayCountTotal);}}AlthoughcodeexternaltotheclassmustaccessthearrayCountTotalstaticvariablethroughtheclassobjectusingCustomArray.
arrayCountTotal,codethatresidesinsidethebodyofthegetPosition()methodcanreferdirectlytothestaticarrayCountTotalvariable.
Thisistrueevenforstaticvariablesinsuperclasses.
ThoughstaticpropertiesarenotinheritedinActionScript3.
0,staticpropertiesinsuperclassesareinscope.
Forexample,theArrayclasshasafewstaticvariables,oneofwhichisaconstantnamedDESCENDING.
CodethatresidesinanArraysubclasscanaccessthestaticconstantDESCENDINGusingasimpleidentifier:publicclassCustomArrayextendsArray{publicfunctiontestStatic():void{trace(DESCENDING);//output:2}}Thevalueofthethisreferencewithinthebodyofaninstancemethodisareferencetotheinstancetowhichthemethodisattached.
Thefollowingcodedemonstratesthatthethisreferencepointstotheinstancethatcontainsthemethod:94LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011classThisTest{functionthisValue():ThisTest{returnthis;}}varmyTest:ThisTest=newThisTest();trace(myTest.
thisValue()==myTest);//output:trueInheritanceofinstancemethodscanbecontrolledwiththekeywordsoverrideandfinal.
Youcanusetheoverrideattributetoredefineaninheritedmethod,andthefinalattributetopreventsubclassesfromoverridingamethod.
GetandsetaccessormethodsGetandsetaccessorfunctions,alsocalledgettersandsetters,allowyoutoadheretotheprogrammingprinciplesofinformationhidingandencapsulationwhileprovidinganeasy-to-useprogramminginterfacefortheclassesthatyoucreate.
Getandsetfunctionsallowyoutokeepyourclasspropertiesprivatetotheclass,butallowusersofyourclasstoaccessthosepropertiesasiftheywereaccessingaclassvariableinsteadofcallingaclassmethod.
Theadvantageofthisapproachisthatitallowsyoutoavoidthetraditionalaccessorfunctionswithunwieldynames,suchasgetPropertyName()andsetPropertyName().
Anotheradvantageofgettersandsettersisthatyoucanavoidhavingtwopublic-facingfunctionsforeachpropertythatallowsbothreadandwriteaccess.
Thefollowingexampleclass,namedGetSet,includesgetandsetaccessorfunctionsnamedpublicAccess()thatprovideaccesstotheprivatevariablenamedprivateProperty:classGetSet{privatevarprivateProperty:String;publicfunctiongetpublicAccess():String{returnprivateProperty;}publicfunctionsetpublicAccess(setValue:String):void{privateProperty=setValue;}}IfyouattempttoaccessthepropertyprivatePropertydirectly,anerroroccurs,asfollows:varmyGetSet:GetSet=newGetSet();trace(myGetSet.
privateProperty);//erroroccursInstead,auseroftheGetSetclassusessomethingthatappearstobeapropertynamedpublicAccess,butthatisreallyapairofgetandsetaccessorfunctionsthatoperateontheprivatepropertynamedprivateProperty.
ThefollowingexampleinstantiatestheGetSetclass,andthensetsthevalueoftheprivatePropertyusingthepublicaccessornamedpublicAccess:varmyGetSet:GetSet=newGetSet();trace(myGetSet.
publicAccess);//output:nullmyGetSet.
publicAccess="hello";trace(myGetSet.
publicAccess);//output:hello95LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Getterandsetterfunctionsalsomakeitpossibletooverridepropertiesthatareinheritedfromasuperclass,somethingthatisnotpossiblewhenyouuseregularclassmembervariables.
Classmembervariablesthataredeclaredusingthevarkeywordcannotbeoverriddeninasubclass.
Propertiesthatarecreatedusinggetterandsetterfunctions,however,donothavethisrestriction.
Youcanusetheoverrideattributeongetterandsetterfunctionsthatareinheritedfromasuperclass.
BoundmethodsAboundmethod,sometimescalledamethodclosure,issimplyamethodthatisextractedfromitsinstance.
Examplesofboundmethodsincludemethodsthatarepassedasargumentstoafunctionorreturnedasvaluesfromafunction.
NewinActionScript3.
0,aboundmethodissimilartoafunctionclosureinthatitretainsitslexicalenvironmentevenwhenextractedfromitsinstance.
Thekeydifference,however,betweenaboundmethodandafunctionclosureisthatthethisreferenceforaboundmethodremainslinked,orbound,totheinstancethatimplementsthemethod.
Inotherwords,thethisreferenceinaboundmethodalwayspointstotheoriginalobjectthatimplementedthemethod.
Forfunctionclosures,thethisreferenceisgeneric,whichmeansthatitpointstowhateverobjectthefunctionisassociatedwithatthetimeitiscalled.
Understandingboundmethodsisimportantifyouusethethiskeyword.
Recallthatthethiskeywordprovidesareferencetoamethod'sparentobject.
MostActionScriptprogrammersexpectthatthethiskeywordalwaysrepresentstheobjectorclassthatcontainsthedefinitionofamethod.
Withoutmethodbinding,however,thiswouldnotalwaysbetrue.
InpreviousversionsofActionScript,forexample,thethisreferencedidnotalwaysrefertotheinstancethatimplementedthemethod.
WhenmethodsareextractedfromaninstanceinActionScript2.
0,notonlyisthethisreferencenotboundtotheoriginalinstance,butalsothemembervariablesandmethodsoftheinstance'sclassarenotavailable.
ThisisnotaprobleminActionScript3.
0,becauseboundmethodsareautomaticallycreatedwhenyoupassamethodasaparameter.
Boundmethodsensurethatthethiskeywordalwaysreferencestheobjectorclassinwhichamethodisdefined.
ThefollowingcodedefinesaclassnamedThisTest,whichcontainsamethodnamedfoo()thatdefinestheboundmethod,andamethodnamedbar()thatreturnstheboundmethod.
CodeexternaltotheclasscreatesaninstanceoftheThisTestclass,callsthebar()method,andstoresthereturnvalueinavariablenamedmyFunc.
classThisTest{privatevarnum:Number=3;functionfoo():void//boundmethoddefined{trace("foo'sthis:"+this);trace("num:"+num);}functionbar():Function{returnfoo;//boundmethodreturned}}varmyTest:ThisTest=newThisTest();varmyFunc:Function=myTest.
bar();trace(this);//output:[objectglobal]myFunc();/*output:foo'sthis:[objectThisTest]output:num:3*/96LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Thelasttwolinesofcodeshowthatthethisreferenceintheboundmethodfoo()stillpointstoaninstanceofThisTestclass,eventhoughthethisreferenceinthelinejustbeforeitpointstotheglobalobject.
Moreover,theboundmethodstoredinthemyFuncvariablestillhasaccesstothemembervariablesoftheThisTestclass.
IfthissamecodeisruninActionScript2.
0,thethisreferenceswouldmatch,andthenumvariablewouldbeundefined.
Oneareawheretheadditionofboundmethodsismostnoticeableiswitheventhandlers,becausetheaddEventListener()methodrequiresthatyoupassafunctionormethodasanargument.
EnumerationswithclassesEnumerationsarecustomdatatypesthatyoucreatetoencapsulateasmallsetofvalues.
ActionScript3.
0doesnotsupportaspecificenumerationfacility,unlikeC++withitsenumkeywordorJavawithitsEnumerationinterface.
Youcan,however,createenumerationsusingclassesandstaticconstants.
Forexample,thePrintJobclassinActionScript3.
0usesanenumerationnamedPrintJobOrientationtostorethevalues"landscape"and"portrait",asshowninthefollowingcode:publicfinalclassPrintJobOrientation{publicstaticconstLANDSCAPE:String="landscape";publicstaticconstPORTRAIT:String="portrait";}Byconvention,anenumerationclassisdeclaredwiththefinalattribute,becausethereisnoneedtoextendtheclass.
Theclassincludesonlystaticmembers,whichmeansthatyoudonotcreateinstancesoftheclass.
Instead,youaccesstheenumerationvaluesdirectlythroughtheclassobject,asshowninthefollowingcodeexcerpt:varpj:PrintJob=newPrintJob();if(pj.
start()){if(pj.
orientation==PrintJobOrientation.
PORTRAIT){.
.
.
}.
.
.
}AlloftheenumerationclassesinActionScript3.
0containonlyvariablesoftypeString,int,oruint.
Theadvantageofusingenumerationsinsteadofliteralstringornumbervaluesisthattypographicalmistakesareeasiertofindwithenumerations.
Ifyoumistypethenameofanenumeration,theActionScriptcompilergeneratesanerror.
Ifyouuseliteralvalues,thecompilerdoesnotcomplainifyouspellawordincorrectlyorusethewrongnumber.
Inthepreviousexample,thecompilergeneratesanerrorifthenameoftheenumerationconstantisincorrect,asthefollowingexcerptshows:if(pj.
orientation==PrintJobOrientation.
PORTRAI)//compilererrorHowever,thecompilerdoesnotgenerateanerrorifyoumisspellastringliteralvalue,asfollows:if(pj.
orientation=="portrai")//nocompilererrorAsecondtechniqueforcreatingenumerationsalsoinvolvescreatingaseparateclasswithstaticpropertiesfortheenumeration.
Thistechniquediffers,however,inthateachofthestaticpropertiescontainsaninstanceoftheclassinsteadofastringorintegervalue.
Forexample,thefollowingcodecreatesanenumerationclassforthedaysoftheweek:97LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011publicfinalclassDay{publicstaticconstMONDAY:Day=newDay();publicstaticconstTUESDAY:Day=newDay();publicstaticconstWEDNESDAY:Day=newDay();publicstaticconstTHURSDAY:Day=newDay();publicstaticconstFRIDAY:Day=newDay();publicstaticconstSATURDAY:Day=newDay();publicstaticconstSUNDAY:Day=newDay();}ThistechniqueisnotusedbyActionScript3.
0butisusedbymanydeveloperswhoprefertheimprovedtypecheckingthatthetechniqueprovides.
Forexample,amethodthatreturnsanenumerationvaluecanrestrictthereturnvaluetotheenumerationdatatype.
Thefollowingcodeshowsnotonlyafunctionthatreturnsadayoftheweek,butalsoafunctioncallthatusestheenumerationtypeasatypeannotation:functiongetDay():Day{vardate:Date=newDate();varretDay:Day;switch(date.
day){case0:retDay=Day.
MONDAY;break;case1:retDay=Day.
TUESDAY;break;case2:retDay=Day.
WEDNESDAY;break;case3:retDay=Day.
THURSDAY;break;case4:retDay=Day.
FRIDAY;break;case5:retDay=Day.
SATURDAY;break;case6:retDay=Day.
SUNDAY;break;}returnretDay;}vardayOfWeek:Day=getDay();YoucanalsoenhancetheDayclasssothatitassociatesanintegerwitheachdayoftheweek,andprovidesatoString()methodthatreturnsastringrepresentationoftheday.
98LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011EmbeddedassetclassesActionScript3.
0usesspecialclasses,calledembeddedassetclasses,torepresentembeddedassets.
Anembeddedassetisanasset,suchasasound,image,orfont,thatisincludedinaSWFfileatcompiletime.
Embeddinganassetinsteadofloadingitdynamicallyensuresthatitisavailableatruntime,butatthecostofincreasedSWFfilesize.
UsingembeddedassetclassesinFlashProfessionalToembedanasset,firstplacetheassetintoaFLAfile'slibrary.
Next,usetheasset'slinkagepropertytoprovideanamefortheasset'sembeddedassetclass.
Ifaclassbythatnamecannotbefoundintheclasspath,aclassisautomaticallygeneratedforyou.
Youcanthencreateaninstanceoftheembeddedassetclassanduseanypropertiesandmethodsdefinedorinheritedbythatclass.
Forexample,thefollowingcodecanbeusedtoplayanembeddedsoundthatislinkedtoanembeddedassetclassnamedPianoMusic:varpiano:PianoMusic=newPianoMusic();varsndChannel:SoundChannel=piano.
play();Alternatively,youcanusethe[Embed]metadatatagtoembedassetsinaFlashProfessionalproject,describednext.
Ifyouusethe[Embed]metadatataginyourcode,FlashProfessionalusestheFlexcompilertocompileyourprojectinsteadoftheFlashProfessionalcompiler.
UsingembeddedassetclassesusingtheFlexcompilerIfyouarecompilingyourcodeusingtheFlexcompiler,toembedanassetinActionScriptcodeusethe[Embed]metadatatag.
Placetheassetinthemainsourcefolderoranotherfolderthatisinyourproject'sbuildpath.
WhentheFlexcompilerencountersanEmbedmetadatatag,itcreatestheembeddedassetclassforyou.
YoucanaccesstheclassthroughavariableofdatatypeClassthatyoudeclareimmediatelyfollowingthe[Embed]metadatatag.
Forexample,thefollowingcodeembedsasoundnamedsound1.
mp3andusesavariablenamedsoundClstostoreareferencetotheembeddedassetclassassociatedwiththatsound.
Theexamplethencreatesaninstanceoftheembeddedassetclassandcallstheplay()methodonthatinstance:package{importflash.
display.
Sprite;importflash.
media.
SoundChannel;importmx.
core.
SoundAsset;publicclassSoundAssetExampleextendsSprite{[Embed(source="sound1.
mp3")]publicvarsoundCls:Class;publicfunctionSoundAssetExample(){varmySound:SoundAsset=newsoundCls()asSoundAsset;varsndChannel:SoundChannel=mySound.
play();}}}AdobeFlashBuilderTousethe[Embed]metadatataginaFlashBuilderActionScriptproject,importanynecessaryclassesfromtheFlexframework.
Forexample,toembedsounds,importthemx.
core.
SoundAssetclass.
TousetheFlexframework,includethefileframework.
swcinyourActionScriptbuildpath.
ThisincreasesthesizeofyourSWFfile.
99LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011AdobeFlexAlternatively,inFlexyoucanembedanassetwiththe@Embed()directiveinanMXMLtagdefinition.
InterfacesAninterfaceisacollectionofmethoddeclarationsthatallowsunrelatedobjectstocommunicatewithoneanother.
Forexample,ActionScript3.
0definestheIEventDispatcherinterface,whichcontainsmethoddeclarationsthataclasscanusetohandleeventobjects.
TheIEventDispatcherinterfaceestablishesastandardwayforobjectstopasseventobjectstooneanother.
ThefollowingcodeshowsthedefinitionoftheIEventDispatcherinterface:publicinterfaceIEventDispatcher{functionaddEventListener(type:String,listener:Function,useCapture:Boolean=false,priority:int=0,useWeakReference:Boolean=false):void;functionremoveEventListener(type:String,listener:Function,useCapture:Boolean=false):void;functiondispatchEvent(event:Event):Boolean;functionhasEventListener(type:String):Boolean;functionwillTrigger(type:String):Boolean;}Interfacesarebasedonthedistinctionbetweenamethod'sinterfaceanditsimplementation.
Amethod'sinterfaceincludesalltheinformationnecessarytocallthatmethod,includingthenameofthemethod,allofitsparameters,anditsreturntype.
Amethod'simplementationincludesnotonlytheinterfaceinformation,butalsotheexecutablestatementsthatcarryoutthemethod'sbehavior.
Aninterfacedefinitioncontainsonlymethodinterfaces,andanyclassthatimplementstheinterfaceisresponsiblefordefiningthemethodimplementations.
InActionScript3.
0,theEventDispatcherclassimplementstheIEventDispatcherinterfacebydefiningalloftheIEventDispatcherinterfacemethodsandaddingmethodbodiestoeachofthemethods.
ThefollowingcodeisanexcerptfromtheEventDispatcherclassdefinition:publicclassEventDispatcherimplementsIEventDispatcher{functiondispatchEvent(event:Event):Boolean{/*implementationstatements*/}.
.
.
}TheIEventDispatcherinterfaceservesasaprotocolthatEventDispatcherinstancesusetoprocesseventobjectsandpassthemtootherobjectsthathavealsoimplementedtheIEventDispatcherinterface.
Anotherwaytodescribeaninterfaceistosaythatitdefinesadatatypejustasaclassdoes.
Accordingly,aninterfacecanbeusedasatypeannotation,justasaclasscan.
Asadatatype,aninterfacecanalsobeusedwithoperators,suchastheisandasoperators,thatrequireadatatype.
Unlikeaclass,however,aninterfacecannotbeinstantiated.
Thisdistinctionhasledmanyprogrammerstothinkofinterfacesasabstractdatatypesandclassesasconcretedatatypes.
100LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011DefininganinterfaceThestructureofaninterfacedefinitionissimilartothatofaclassdefinition,exceptthataninterfacecancontainonlymethodswithnomethodbodies.
Interfacescannotincludevariablesorconstantsbutcanincludegettersandsetters.
Todefineaninterface,usetheinterfacekeyword.
Forexample,thefollowinginterface,IExternalizable,ispartoftheflash.
utilspackageinActionScript3.
0.
TheIExternalizableinterfacedefinesaprotocolforserializinganobject,whichmeansconvertinganobjectintoaformatsuitableforstorageonadeviceorfortransportacrossanetwork.
publicinterfaceIExternalizable{functionwriteExternal(output:IDataOutput):void;functionreadExternal(input:IDataInput):void;}TheIExternalizableinterfaceisdeclaredwiththepublicaccesscontrolmodifier.
Interfacedefinitionscanonlybemodifiedbythepublicandinternalaccesscontrolspecifiers.
Themethoddeclarationsinsideaninterfacedefinitioncannothaveanyaccesscontrolspecifiers.
ActionScript3.
0followsaconventioninwhichinterfacenamesbeginwithanuppercaseI,butyoucanuseanylegalidentifierasaninterfacename.
Interfacedefinitionsareoftenplacedatthetoplevelofapackage.
Interfacedefinitionscannotbeplacedinsideaclassdefinitionorinsideanotherinterfacedefinition.
Interfacescanextendoneormoreotherinterfaces.
Forexample,thefollowinginterface,IExample,extendstheIExternalizableinterface:publicinterfaceIExampleextendsIExternalizable{functionextra():void;}AnyclassthatimplementstheIExampleinterfacemustincludeimplementationsnotonlyfortheextra()method,butalsoforthewriteExternal()andreadExternal()methodsinheritedfromtheIExternalizableinterface.
ImplementinganinterfaceinaclassAclassistheonlyActionScript3.
0languageelementthatcanimplementaninterface.
Usetheimplementskeywordinaclassdeclarationtoimplementoneormoreinterfaces.
Thefollowingexampledefinestwointerfaces,IAlphaandIBeta,andaclass,Alpha,thatimplementsthemboth:interfaceIAlpha{functionfoo(str:String):String;}interfaceIBeta{functionbar():void;}classAlphaimplementsIAlpha,IBeta{publicfunctionfoo(param:String):String{}publicfunctionbar():void{}}Inaclassthatimplementsaninterface,implementedmethodsmustdothefollowing:Usethepublicaccesscontrolidentifier.
101LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Usethesamenameastheinterfacemethod.
Havethesamenumberofparameters,eachwithdatatypesthatmatchtheinterfacemethodparameterdatatypes.
Usethesamereturntype.
publicfunctionfoo(param:String):String{}Youdohavesomeflexibility,however,inhowyounametheparametersofmethodsthatyouimplement.
Althoughthenumberofparametersandthedatatypeofeachparameterintheimplementedmethodmustmatchthatoftheinterfacemethod,theparameternamesdonotneedtomatch.
Forexample,inthepreviousexampletheparameteroftheAlpha.
foo()methodisnamedparam:ButtheparameterisnamedstrintheIAlpha.
foo()interfacemethod:functionfoo(str:String):String;Youalsohavesomeflexibilitywithdefaultparametervalues.
Aninterfacedefinitioncanincludefunctiondeclarationswithdefaultparametervalues.
Amethodthatimplementssuchafunctiondeclarationmusthaveadefaultparametervaluethatisamemberofthesamedatatypeasthevaluespecifiedintheinterfacedefinition,buttheactualvaluedoesnothavetomatch.
Forexample,thefollowingcodedefinesaninterfacethatcontainsamethodwithadefaultparametervalueof3:interfaceIGamma{functiondoSomething(param:int=3):void;}ThefollowingclassdefinitionimplementstheIGammainterfacebutusesadifferentdefaultparametervalue:classGammaimplementsIGamma{publicfunctiondoSomething(param:int=4):void{}}Thereasonforthisflexibilityisthattherulesforimplementinganinterfacearedesignedspecificallytoensuredatatypecompatibility,andrequiringidenticalparameternamesanddefaultparametervaluesisnotnecessarytoachievethatobjective.
InheritanceInheritanceisaformofcodereusethatallowsprogrammerstodevelopnewclassesthatarebasedonexistingclasses.
Theexistingclassesareoftencalledbaseclassesorsuperclasses,whilethenewclassesarecalledsubclasses.
Akeyadvantageofinheritanceisthatitallowsyoutoreusecodefromabaseclassyetleavetheexistingcodeunmodified.
Moreover,inheritancerequiresnochangestothewaythatotherclassesinteractwiththebaseclass.
Ratherthanmodifyinganexistingclassthatmayhavebeenthoroughlytestedormayalreadybeinuse,usinginheritanceyoucantreatthatclassasanintegratedmodulethatyoucanextendwithadditionalpropertiesormethods.
Accordingly,youusetheextendskeywordtoindicatethataclassinheritsfromanotherclass.
Inheritancealsoallowsyoutotakeadvantageofpolymorphisminyourcode.
Polymorphismistheabilitytouseasinglemethodnameforamethodthatbehavesdifferentlywhenappliedtodifferentdatatypes.
AsimpleexampleisabaseclassnamedShapewithtwosubclassesnamedCircleandSquare.
TheShapeclassdefinesamethodnamedarea(),whichreturnstheareaoftheshape.
Ifpolymorphismisimplemented,youcancallthearea()methodonobjectsoftypeCircleandSquareandhavethecorrectcalculationsdoneforyou.
Inheritanceenablespolymorphismbyallowingsubclassestoinheritandredefine,oroverride,methodsfromthebaseclass.
Inthefollowingexample,thearea()methodisredefinedbytheCircleandSquareclasses:102LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011classShape{publicfunctionarea():Number{returnNaN;}}classCircleextendsShape{privatevarradius:Number=1;overridepublicfunctionarea():Number{return(Math.
PI*(radius*radius));}}classSquareextendsShape{privatevarside:Number=1;overridepublicfunctionarea():Number{return(side*side);}}varcir:Circle=newCircle();trace(cir.
area());//output:3.
141592653589793varsq:Square=newSquare();trace(sq.
area());//output:1Becauseeachclassdefinesadatatype,theuseofinheritancecreatesaspecialrelationshipbetweenabaseclassandaclassthatextendsit.
Asubclassisguaranteedtopossessallthepropertiesofitsbaseclass,whichmeansthataninstanceofasubclasscanalwaysbesubstitutedforaninstanceofthebaseclass.
Forexample,ifamethoddefinesaparameteroftypeShape,itislegaltopassanargumentoftypeCirclebecauseCircleextendsShape,asinthefollowing:functiondraw(shapeToDraw:Shape){}varmyCircle:Circle=newCircle();draw(myCircle);InstancepropertiesandinheritanceAninstanceproperty,whetherdefinedwiththefunction,var,orconstkeywords,isinheritedbyallsubclassesaslongasthepropertyisnotdeclaredwiththeprivateattributeinthebaseclass.
Forexample,theEventclassinActionScript3.
0hasanumberofsubclassesthatinheritpropertiescommontoalleventobjects.
Forsometypesofevents,theEventclasscontainsallthepropertiesnecessarytodefinetheevent.
ThesetypesofeventsdonotrequireinstancepropertiesbeyondthosedefinedintheEventclass.
Examplesofsucheventsarethecompleteevent,whichoccurswhendatahasloadedsuccessfully,andtheconnectevent,whichoccurswhenanetworkconnectionhasbeenestablished.
ThefollowingexampleisanexcerptfromtheEventclassthatshowssomeofthepropertiesandmethodsthatareinheritedbysubclasses.
Becausethepropertiesareinherited,aninstanceofanysubclasscanaccesstheseproperties.
103LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011publicclassEvent{publicfunctiongettype():String;publicfunctiongetbubbles():Boolean;.
.
.
publicfunctionstopPropagation():void{}publicfunctionstopImmediatePropagation():void{}publicfunctionpreventDefault():void{}publicfunctionisDefaultPrevented():Boolean{}.
.
.
}OthertypesofeventsrequireuniquepropertiesnotavailableintheEventclass.
TheseeventsaredefinedusingsubclassesoftheEventclasssothatnewpropertiescanbeaddedtothepropertiesdefinedintheEventclass.
AnexampleofsuchasubclassistheMouseEventclass,whichaddspropertiesuniquetoeventsassociatedwithmousemovementormouseclicks,suchasthemouseMoveandclickevents.
ThefollowingexampleisanexcerptfromtheMouseEventclassthatshowsthedefinitionofpropertiesthatexistonthesubclassbutnotonthebaseclass:publicclassMouseEventextendsEvent{publicstaticconstCLICK:String="click";publicstaticconstMOUSE_MOVE:String="mouseMove";.
.
.
publicfunctiongetstageX():Number{}publicfunctiongetstageY():Number{}.
.
.
}AccesscontrolspecifiersandinheritanceIfapropertyisdeclaredwiththepublickeyword,thepropertyisvisibletocodeanywhere.
Thismeansthatthepublickeyword,unliketheprivate,protected,andinternalkeywords,placesnorestrictionsonpropertyinheritance.
Ifapropertyisdeclaredwithprivatekeyword,itisvisibleonlyintheclassthatdefinesit,whichmeansthatitisnotinheritedbyanysubclasses.
ThisbehaviorisdifferentfrompreviousversionsofActionScript,wheretheprivatekeywordbehavedmoreliketheActionScript3.
0protectedkeyword.
Theprotectedkeywordindicatesthatapropertyisvisiblenotonlywithintheclassthatdefinesit,butalsotoallsubclasses.
UnliketheprotectedkeywordintheJavaprogramminglanguage,theprotectedkeywordinActionScript3.
0doesnotmakeapropertyvisibletoallotherclassesinthesamepackage.
InActionScript3.
0,onlysubclassescanaccessapropertydeclaredwiththeprotectedkeyword.
Moreover,aprotectedpropertyisvisibletoasubclasswhetherthesubclassisinthesamepackageasthebaseclassorinadifferentpackage.
Tolimitthevisibilityofapropertytothepackageinwhichitisdefined,usetheinternalkeywordordonotuseanyaccesscontrolspecifier.
Theinternalaccesscontrolspecifieristhedefaultaccesscontrolspecifierthatapplieswhenoneisnotspecified.
Apropertymarkedasinternalisonlyinheritedbyasubclassthatresidesinthesamepackage.
Youcanusethefollowingexampletoseehoweachoftheaccesscontrolspecifiersaffectsinheritanceacrosspackageboundaries.
ThefollowingcodedefinesamainapplicationclassnamedAccessControlandtwootherclassesnamedBaseandExtender.
TheBaseclassisinapackagenamedfooandtheExtenderclass,whichisasubclassoftheBaseclass,isinapackagenamedbar.
TheAccessControlclassimportsonlytheExtenderclassandcreatesaninstanceofExtenderthatattemptstoaccessavariablenamedstrthatisdefinedintheBaseclass.
Thestrvariableisdeclaredaspublicsothatthecodecompilesandrunsasshowninthefollowingexcerpt:104LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011//Base.
asinafoldernamedfoopackagefoo{publicclassBase{publicvarstr:String="hello";//changepubliconthisline}}//Extender.
asinafoldernamedbarpackagebar{importfoo.
Base;publicclassExtenderextendsBase{publicfunctiongetString():String{returnstr;}}}//mainapplicationclassinfilenamedAccessControl.
aspackage{importflash.
display.
MovieClip;importbar.
Extender;publicclassAccessControlextendsMovieClip{publicfunctionAccessControl(){varmyExt:Extender=newExtender();trace(myExt.
str);//errorifstrisnotpublictrace(myExt.
getString());//errorifstrisprivateorinternal}}}Toseehowtheotheraccesscontrolspecifiersaffectcompilationandexecutionoftheprecedingexample,changethestrvariable'saccesscontrolspecifiertoprivate,protected,orinternalafterdeletingorcommentingoutthefollowinglinefromtheAccessControlclass:trace(myExt.
str);//errorifstrisnotpublicOverridingvariablesnotpermittedPropertiesthataredeclaredwiththevarorconstkeywordsareinheritedbutcannotbeoverridden.
Tooverrideapropertymeanstoredefinethepropertyinasubclass.
Theonlytypeofpropertythatcanbeoverriddenaregetandsetaccessors(propertiesdeclaredwiththefunctionkeyword).
Althoughyoucannotoverrideaninstancevariable,youcanachievesimilarfunctionalitybycreatinggetterandsettermethodsfortheinstancevariableandoverridingthemethods.
105LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011OverridingmethodsTooverrideamethodmeanstoredefinethebehaviorofaninheritedmethod.
Staticmethodsarenotinheritedandcannotbeoverridden.
Instancemethods,however,areinheritedbysubclassesandcanbeoverriddenaslongasthefollowingtwocriteriaaremet:Theinstancemethodisnotdeclaredwiththefinalkeywordinthebaseclass.
Whenusedwithaninstancemethod,thefinalkeywordindicatestheprogrammer'sintenttopreventsubclassesfromoverridingthemethod.
Theinstancemethodisnotdeclaredwiththeprivateaccesscontrolspecifierinthebaseclass.
Ifamethodismarkedasprivateinthebaseclass,thereisnoneedtousetheoverridekeywordwhendefininganidenticallynamedmethodinthesubclass,becausethebaseclassmethodisnotvisibletothesubclass.
Tooverrideaninstancemethodthatmeetsthesecriteria,themethoddefinitioninthesubclassmustusetheoverridekeywordandmustmatchthesuperclassversionofthemethodinthefollowingways:Theoverridemethodmusthavethesamelevelofaccesscontrolasthebaseclassmethod.
Methodsmarkedasinternalhavethesamelevelofaccesscontrolasmethodsthathavenoaccesscontrolspecifier.
Theoverridemethodmusthavethesamenumberofparametersasthebaseclassmethod.
Theoverridemethodparametersmusthavethesamedatatypeannotationsastheparametersinthebaseclassmethod.
Theoverridemethodmusthavethesamereturntypeasthebaseclassmethod.
Thenamesoftheparametersintheoverridemethod,however,donothavetomatchthenamesoftheparametersinthebaseclass,aslongasthenumberofparametersandthedatatypeofeachparametermatches.
ThesuperstatementWhenoverridingamethod,programmersoftenwanttoaddtothebehaviorofthesuperclassmethodtheyareoverridinginsteadofcompletelyreplacingthebehavior.
Thisrequiresamechanismthatallowsamethodinasubclasstocallthesuperclassversionofitself.
Thesuperstatementprovidessuchamechanism,inthatitcontainsareferencetotheimmediatesuperclass.
ThefollowingexampledefinesaclassnamedBasethatcontainsamethodnamedthanks()andasubclassoftheBaseclassnamedExtenderthatoverridesthethanks()method.
TheExtender.
thanks()methodusesthesuperstatementtocallBase.
thanks().
106LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011package{importflash.
display.
MovieClip;publicclassSuperExampleextendsMovieClip{publicfunctionSuperExample(){varmyExt:Extender=newExtender()trace(myExt.
thanks());//output:Mahalonuiloa}}}classBase{publicfunctionthanks():String{return"Mahalo";}}classExtenderextendsBase{overridepublicfunctionthanks():String{returnsuper.
thanks()+"nuiloa";}}OverridinggettersandsettersAlthoughyoucannotoverridevariablesdefinedinasuperclass,youcanoverridegettersandsetters.
Forexample,thefollowingcodeoverridesagetternamedcurrentLabelthatisdefinedintheMovieClipclassinActionScript3.
0.
:package{importflash.
display.
MovieClip;publicclassOverrideExampleextendsMovieClip{publicfunctionOverrideExample(){trace(currentLabel)}overridepublicfunctiongetcurrentLabel():String{varstr:String="Override:";str+=super.
currentLabel;returnstr;}}}Theoutputofthetrace()statementintheOverrideExampleclassconstructorisOverride:null,whichshowsthattheexamplewasabletooverridetheinheritedcurrentLabelproperty.
107LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011StaticpropertiesnotinheritedStaticpropertiesarenotinheritedbysubclasses.
Thismeansthatstaticpropertiescannotbeaccessedthroughaninstanceofasubclass.
Astaticpropertycanbeaccessedonlythroughtheclassobjectonwhichitisdefined.
Forexample,thefollowingcodedefinesabaseclassnamedBaseandasubclassthatextendsBasenamedExtender.
AstaticvariablenamedtestisdefinedintheBaseclass.
Thecodeaswritteninthefollowingexcerptdoesnotcompileinstrictmodeandgeneratesarun-timeerrorinstandardmode.
package{importflash.
display.
MovieClip;publicclassStaticExampleextendsMovieClip{publicfunctionStaticExample(){varmyExt:Extender=newExtender();trace(myExt.
test);//error}}}classBase{publicstaticvartest:String="static";}classExtenderextendsBase{}Theonlywaytoaccessthestaticvariabletestisthroughtheclassobject,asshowninthefollowingcode:Base.
test;Itispermissible,however,todefineaninstancepropertyusingthesamenameasastaticproperty.
Suchaninstancepropertycanbedefinedinthesameclassasthestaticpropertyorinasubclass.
Forexample,theBaseclassintheprecedingexamplecouldhaveaninstancepropertynamedtest.
ThefollowingcodecompilesandexecutesbecausetheinstancepropertyisinheritedbytheExtenderclass.
Thecodewouldalsocompileandexecuteifthedefinitionofthetestinstancevariableismoved,butnotcopied,totheExtenderclass.
package{importflash.
display.
MovieClip;publicclassStaticExampleextendsMovieClip{publicfunctionStaticExample(){varmyExt:Extender=newExtender();trace(myExt.
test);//output:instance}}}classBase{publicstaticvartest:String="static";publicvartest:String="instance";}classExtenderextendsBase{}108LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011StaticpropertiesandthescopechainAlthoughstaticpropertiesarenotinherited,theyarewithinthescopechainoftheclassthatdefinesthemandanysubclassofthatclass.
Assuch,staticpropertiesaresaidtobeinscopeofboththeclassinwhichtheyaredefinedandanysubclasses.
Thismeansthatastaticpropertyisdirectlyaccessiblewithinthebodyoftheclassthatdefinesthestaticpropertyandanysubclassofthatclass.
ThefollowingexamplemodifiestheclassesdefinedinthepreviousexampletoshowthatthestatictestvariabledefinedintheBaseclassisinscopeoftheExtenderclass.
Inotherwords,theExtenderclasscanaccessthestatictestvariablewithoutprefixingthevariablewiththenameoftheclassthatdefinestest.
package{importflash.
display.
MovieClip;publicclassStaticExampleextendsMovieClip{publicfunctionStaticExample(){varmyExt:Extender=newExtender();}}}classBase{publicstaticvartest:String="static";}classExtenderextendsBase{publicfunctionExtender(){trace(test);//output:static}}Ifaninstancepropertyisdefinedthatusesthesamenameasastaticpropertyinthesameclassorasuperclass,theinstancepropertyhashigherprecedenceinthescopechain.
Theinstancepropertyissaidtoshadowthestaticproperty,whichmeansthatthevalueoftheinstancepropertyisusedinsteadofthevalueofthestaticproperty.
Forexample,thefollowingcodeshowsthatiftheExtenderclassdefinesaninstancevariablenamedtest,thetrace()statementusesthevalueoftheinstancevariableinsteadofthevalueofthestaticvariable.
:109LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011package{importflash.
display.
MovieClip;publicclassStaticExampleextendsMovieClip{publicfunctionStaticExample(){varmyExt:Extender=newExtender();}}}classBase{publicstaticvartest:String="static";}classExtenderextendsBase{publicvartest:String="instance";publicfunctionExtender(){trace(test);//output:instance}}AdvancedtopicsHistoryofActionScriptOOPsupportBecauseActionScript3.
0buildsuponpreviousversionsofActionScript,itmaybehelpfultounderstandhowtheActionScriptobjectmodelhasevolved.
ActionScriptbeganasasimplescriptingmechanismforearlyversionsofFlashProfessional.
Later,programmersbeganbuildingincreasinglycomplexapplicationswithActionScript.
Inresponsetotheneedsofsuchprogrammers,eachsubsequentreleasehasaddedlanguagefeaturesthatfacilitatethecreationofcomplexapplications.
ActionScript1.
0ActionScript1.
0istheversionofthelanguageusedinFlashPlayer6andearlier.
Evenatthisearlystageofdevelopment,theActionScriptobjectmodelwasbasedontheconceptoftheobjectasafundamentaldatatype.
AnActionScriptobjectisacompounddatatypewithagroupofproperties.
Whendiscussingtheobjectmodel,thetermpropertiesincludeseverythingthatisattachedtoanobject,suchasvariables,functions,ormethods.
AlthoughthisfirstgenerationofActionScriptdoesnotsupportthedefinitionofclasseswithaclasskeyword,youcandefineaclassusingaspecialkindofobjectcalledaprototypeobject.
Insteadofusingaclasskeywordtocreateanabstractclassdefinitionthatyouinstantiateintoconcreteobjects,asyoudoinclass-basedlanguageslikeJavaandC++,prototype-basedlanguageslikeActionScript1.
0useanexistingobjectasamodel(orprototype)forotherobjects.
Whileobjectsinaclass-basedlanguagemaypointtoaclassthatservesasitstemplate,objectsinaprototype-basedlanguagepointinsteadtoanotherobject,itsprototype,thatservesasitstemplate.
110LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011TocreateaclassinActionScript1.
0,youdefineaconstructorfunctionforthatclass.
InActionScript,functionsareactualobjects,notjustabstractdefinitions.
Theconstructorfunctionthatyoucreateservesastheprototypicalobjectforinstancesofthatclass.
ThefollowingcodecreatesaclassnamedShapeanddefinesonepropertynamedvisiblethatissettotruebydefault://baseclassfunctionShape(){}//Createapropertynamedvisible.
Shape.
prototype.
visible=true;ThisconstructorfunctiondefinesaShapeclassthatyoucaninstantiatewiththenewoperator,asfollows:myShape=newShape();JustastheShape()constructorfunctionobjectservesastheprototypeforinstancesoftheShapeclass,itcanalsoserveastheprototypeforsubclassesofShape—thatis,otherclassesthatextendtheShapeclass.
ThecreationofaclassthatisasubclassoftheShapeclassisatwo-stepprocess.
First,createtheclassbydefiningaconstructorfunctionfortheclass,asfollows://childclassfunctionCircle(id,radius){this.
id=id;this.
radius=radius;}Second,usethenewoperatortodeclarethattheShapeclassistheprototypefortheCircleclass.
Bydefault,anyclassyoucreateusestheObjectclassasitsprototype,whichmeansthatCircle.
prototypecurrentlycontainsagenericobject(aninstanceoftheObjectclass).
TospecifythatCircle'sprototypeisShapeinsteadofObject,usethefollowingcodetochangethevalueofCircle.
prototypesothatitcontainsaShapeobjectinsteadofagenericobject://MakeCircleasubclassofShape.
Circle.
prototype=newShape();TheShapeclassandtheCircleclassarenowlinkedtogetherinaninheritancerelationshipthatiscommonlyknownastheprototypechain.
Thediagramillustratestherelationshipsinaprototypechain:ThebaseclassattheendofeveryprototypechainistheObjectclass.
TheObjectclasscontainsastaticpropertynamedObject.
prototypethatpointstothebaseprototypeobjectforallobjectscreatedinActionScript1.
0.
ThenextobjectintheexampleprototypechainistheShapeobject.
ThisisbecausetheShape.
prototypepropertywasneverexplicitlyset,soitstillholdsagenericobject(aninstanceoftheObjectclass).
ThefinallinkinthischainistheCircleclass,whichislinkedtoitsprototype,theShapeclass(theCircle.
prototypepropertyholdsaShapeobject).
IfyoucreateaninstanceoftheCircleclass,asinthefollowingexample,theinstanceinheritstheprototypechainoftheCircleclass://CreateaninstanceoftheCircleclass.
myCircle=newCircle();Object.
prototypeShape.
prototypeCircle.
prototype111LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011RecallthattheexampleincludedapropertynamedvisibleasamemberoftheShapeclass.
Inthisexample,thevisiblepropertydoesnotexistasapartofthemyCircleobject,onlyasamemberoftheShapeobject,yetthefollowinglineofcodeoutputstrue:trace(myCircle.
visible);//output:trueTheruntimeisabletoascertainthatthemyCircleobjectinheritsthevisiblepropertybywalkinguptheprototypechain.
Whenexecutingthiscode,theruntimefirstsearchesthroughthepropertiesofthemyCircleobjectforapropertynamedvisible,butdoesnotfindsuchaproperty.
ItlooksnextintheCircle.
prototypeobject,butstilldoesnotfindapropertynamedvisible.
Continuinguptheprototypechain,itfinallyfindsthevisiblepropertydefinedontheShape.
prototypeobjectandoutputsthevalueofthatproperty.
Intheinterestofsimplicity,manyofthedetailsandintricaciesoftheprototypechainareomitted.
InsteadthegoalistoprovideenoughinformationtohelpyouunderstandtheActionScript3.
0objectmodel.
ActionScript2.
0ActionScript2.
0introducednewkeywordssuchasclass,extends,public,andprivate,thatallowedyoutodefineclassesinawaythatisfamiliartoanyonewhoworkswithclass-basedlanguageslikeJavaandC++.
It'simportanttounderstandthattheunderlyinginheritancemechanismdidnotchangebetweenActionScript1.
0andActionScript2.
0.
ActionScript2.
0merelyaddedanewsyntaxfordefiningclasses.
Theprototypechainworksthesamewayinbothversionsofthelanguage.
ThenewsyntaxintroducedbyActionScript2.
0,showninthefollowingexcerpt,allowsyoutodefineclassesinawaythatmanyprogrammersfindmoreintuitive://baseclassclassShape{varvisible:Boolean=true;}NotethatActionScript2.
0alsointroducedtypeannotationsforusewithcompile-timetypechecking.
ThisallowsyoutodeclarethatthevisiblepropertyinthepreviousexampleshouldcontainonlyaBooleanvalue.
Thenewextendskeywordalsosimplifiestheprocessofcreatingasubclass.
Inthefollowingexample,thetwo-stepprocessnecessaryinActionScript1.
0isaccomplishedinonestepwiththeextendskeyword://childclassclassCircleextendsShape{varid:Number;varradius:Number;functionCircle(id,radius){this.
id=id;this.
radius=radius;}}Theconstructorisnowdeclaredaspartoftheclassdefinition,andtheclasspropertiesidandradiusmustalsobedeclaredexplicitly.
ActionScript2.
0alsoaddedsupportforthedefinitionofinterfaces,whichallowyoutofurtherrefineyourobject-orientedprogramswithformallydefinedprotocolsforinter-objectcommunication.
112LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011TheActionScript3.
0classobjectAcommonobject-orientedprogrammingparadigm,mostcommonlyassociatedwithJavaandC++,usesclassestodefinetypesofobjects.
Programminglanguagesthatadoptthisparadigmalsotendtouseclassestoconstructinstancesofthedatatypethattheclassdefines.
ActionScriptusesclassesforbothofthesepurposes,butitsrootsasaprototype-basedlanguageaddaninterestingcharacteristic.
ActionScriptcreatesforeachclassdefinitionaspecialclassobjectthatallowssharingofbothbehaviorandstate.
FormanyActionScriptprogrammers,however,thisdistinctionmayhavenopracticalcodingimplications.
ActionScript3.
0isdesignedsuchthatyoucancreatesophisticatedobject-orientedActionScriptapplicationswithoutusing,orevenunderstanding,thesespecialclassobjects.
ThefollowingdiagramshowsthestructureofaclassobjectthatrepresentsasimpleclassnamedAthatisdefinedwiththestatementclassA{}:Eachrectangleinthediagramrepresentsanobject.
EachobjectinthediagramhasasubscriptcharacterAtorepresentthatitbelongstoclassA.
Theclassobject(CA)containsreferencestoanumberofotherimportantobjects.
Aninstancetraitsobject(TA)storestheinstancepropertiesthataredefinedwithinaclassdefinition.
Aclasstraitsobject(TCA)representstheinternaltypeoftheclassandstoresthestaticpropertiesdefinedbytheclass(thesubscriptcharacterCstandsfor"class").
Theprototypeobject(PA)alwaysmeanstheclassobjecttowhichitwasoriginallyattachedthroughtheconstructorproperty.
ThetraitsobjectThetraitsobject,whichisnewinActionScript3.
0,wasimplementedwithperformanceinmind.
InpreviousversionsofActionScript,namelookupcouldbeatime-consumingprocessasFlashPlayerwalkedtheprototypechain.
InActionScript3.
0,namelookupismuchmoreefficientandlesstimeconsuming,becauseinheritedpropertiesarecopieddownfromsuperclassesintothetraitsobjectofsubclasses.
Thetraitsobjectisnotdirectlyaccessibletoprogrammercode,butitspresencecanbefeltbytheimprovementsinperformanceandmemoryusage.
ThetraitsobjectprovidestheAVM2withdetailedinformationaboutthelayoutandcontentsofaclass.
Withsuchknowledge,theAVM2isabletosignificantlyreduceexecutiontime,becauseitcanoftengeneratedirectmachineinstructionstoaccesspropertiesorcallmethodsdirectlywithoutatime-consumingnamelookup.
Thankstothetraitsobject,anobject'smemoryfootprintcanbesignificantlysmallerthanasimilarobjectinpreviousversionsofActionScript.
Forexample,ifaclassissealed(thatis,theclassisnotdeclareddynamic),aninstanceoftheclassdoesnotneedahashtablefordynamicallyaddedproperties,andcanholdlittlemorethanapointertothetraitsobjectsandsomeslotsforthefixedpropertiesdefinedintheclass.
Asaresult,anobjectthatrequired100bytesofmemoryinActionScript2.
0couldrequireaslittleas20bytesofmemoryinActionScript3.
0.
TCAPACATAClass.
prototypeObject.
prototypedelegateconstructordelegateprototypetypetraits113LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Note:Thetraitsobjectisaninternalimplementationdetail,andthereisnoguaranteethatitwillnotchangeorevendisappearinfutureversionsofActionScript.
TheprototypeobjectEveryActionScriptclassobjecthasapropertynamedprototype,whichisareferencetotheclass'sprototypeobject.
TheprototypeobjectisalegacyofActionScript'srootsasprototype-basedlanguage.
Formoreinformation,seeHistoryofActionScriptOOPsupport.
Theprototypepropertyisread-only,whichmeansthatitcannotbemodifiedtopointtodifferentobjects.
ThisdiffersfromtheclassprototypepropertyinpreviousversionsofActionScript,wheretheprototypecouldbereassignedsothatitpointedtoadifferentclass.
Althoughtheprototypepropertyisread-only,theprototypeobjectthatitreferencesisnot.
Inotherwords,newpropertiescanbeaddedtotheprototypeobject.
Propertiesaddedtotheprototypeobjectaresharedamongallinstancesoftheclass.
Theprototypechain,whichwastheonlyinheritancemechanisminpreviousversionsofActionScript,servesonlyasecondaryroleinActionScript3.
0.
Theprimaryinheritancemechanism,fixedpropertyinheritance,ishandledinternallybythetraitsobject.
Afixedpropertyisavariableormethodthatisdefinedaspartofaclassdefinition.
Fixedpropertyinheritanceisalsocalledclassinheritance,becauseitistheinheritancemechanismthatisassociatedwithkeywordssuchasclass,extends,andoverride.
Theprototypechainprovidesanalternativeinheritancemechanismthatismoredynamicthanfixedpropertyinheritance.
Youcanaddpropertiestoaclass'sprototypeobjectnotonlyaspartoftheclassdefinition,butalsoatruntimethroughtheclassobject'sprototypeproperty.
Note,however,thatifyousetthecompilertostrictmode,youmaynotbeabletoaccesspropertiesaddedtoaprototypeobjectunlessyoudeclareaclasswiththedynamickeyword.
AgoodexampleofaclasswithseveralpropertiesattachedtotheprototypeobjectistheObjectclass.
TheObjectclass'stoString()andvalueOf()methodsareactuallyfunctionsassignedtopropertiesoftheObjectclass'sprototypeobject.
Thefollowingisanexampleofhowthedeclarationofthesemethodscould,intheory,look(theactualimplementationdiffersslightlybecauseofimplementationdetails):publicdynamicclassObject{prototype.
toString=function(){//statements};prototype.
valueOf=function(){//statements};}Asmentionedpreviously,youcanattachapropertytoaclass'sprototypeobjectoutsidetheclassdefinition.
Forexample,thetoString()methodcanalsobedefinedoutsidetheObjectclassdefinition,asfollows:Object.
prototype.
toString=function(){//statements};114LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Unlikefixedpropertyinheritance,however,prototypeinheritancedoesnotrequiretheoverridekeywordifyouwanttoredefineamethodinasubclass.
Forexample.
ifyouwanttoredefinethevalueOf()methodinasubclassoftheObjectclass,youhavethreeoptions.
First,youcandefineavalueOf()methodonthesubclass'sprototypeobjectinsidetheclassdefinition.
ThefollowingcodecreatesasubclassofObjectnamedFooandredefinesthevalueOf()methodonFoo'sprototypeobjectaspartoftheclassdefinition.
BecauseeveryclassinheritsfromObject,itisnotnecessarytousetheextendskeyword.
dynamicclassFoo{prototype.
valueOf=function(){return"InstanceofFoo";};}Second,youcandefineavalueOf()methodonFoo'sprototypeobjectoutsidetheclassdefinition,asshowninthefollowingcode:Foo.
prototype.
valueOf=function(){return"InstanceofFoo";};Third,youcandefineafixedpropertynamedvalueOf()aspartoftheFooclass.
Thistechniquediffersfromtheothersinthatitmixesfixedpropertyinheritancewithprototypeinheritance.
AnysubclassofFoothatwantstoredefinevalueOf()mustusetheoverridekeyword.
ThefollowingcodeshowsvalueOf()definedasafixedpropertyinFoo:classFoo{functionvalueOf():String{return"InstanceofFoo";}}TheAS3namespaceTheexistenceoftwoseparateinheritancemechanisms,fixedpropertyinheritanceandprototypeinheritance,createsaninterestingcompatibilitychallengewithrespecttothepropertiesandmethodsofthecoreclasses.
CompatibilitywiththeECMAScriptlanguagespecificationonwhichActionScriptisbasedrequirestheuseofprototypeinheritance,whichmeansthatthepropertiesandmethodsofacoreclassaredefinedontheprototypeobjectofthatclass.
Ontheotherhand,compatibilitywithActionScript3.
0callsfortheuseoffixedpropertyinheritance,whichmeansthatthepropertiesandmethodsofacoreclassaredefinedintheclassdefinitionusingtheconst,var,andfunctionkeywords.
Moreover,theuseoffixedpropertiesinsteadoftheprototypeversionscanleadtosignificantincreasesinrun-timeperformance.
ActionScript3.
0solvesthisproblembyusingbothprototypeinheritanceandfixedpropertyinheritanceforthecoreclasses.
Eachcoreclasscontainstwosetsofpropertiesandmethods.
OnesetisdefinedontheprototypeobjectforcompatibilitywiththeECMAScriptspecification,andtheothersetisdefinedwithfixedpropertiesandtheAS3namespaceforcompatibilitywithActionScript3.
0.
115LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011TheAS3namespaceprovidesaconvenientmechanismforchoosingbetweenthetwosetsofpropertiesandmethods.
IfyoudonotusetheAS3namespace,aninstanceofacoreclassinheritsthepropertiesandmethodsdefinedonthecoreclass'sprototypeobject.
IfyoudecidetousetheAS3namespace,aninstanceofacoreclassinheritstheAS3versionsbecausefixedpropertiesarealwayspreferredoverprototypeproperties.
Inotherwords,wheneverafixedpropertyisavailable,itisalwaysusedinsteadofanidenticallynamedprototypeproperty.
YoucanselectivelyusetheAS3namespaceversionofapropertyormethodbyqualifyingitwiththeAS3namespace.
Forexample,thefollowingcodeusestheAS3versionoftheArray.
pop()method:varnums:Array=newArray(1,2,3);nums.
AS3::pop();trace(nums);//output:1,2Alternatively,youcanusetheusenamespacedirectivetoopentheAS3namespaceforallthedefinitionswithinablockofcode.
Forexample,thefollowingcodeusestheusenamespacedirectivetoopentheAS3namespaceforboththepop()andpush()methods:usenamespaceAS3;varnums:Array=newArray(1,2,3);nums.
pop();nums.
push(5);trace(nums)//output:1,2,5ActionScript3.
0alsoprovidescompileroptionsforeachsetofpropertiessothatyoucanapplytheAS3namespacetoyourentireprogram.
The-as3compileroptionrepresentstheAS3namespace,andthe-escompileroptionrepresentstheprototypeinheritanceoption(esstandsforECMAScript).
ToopentheAS3namespaceforyourentireprogram,setthe-as3compileroptiontotrueandthe-escompileroptiontofalse.
Tousetheprototypeversions,setthecompileroptionstotheoppositevalues.
ThedefaultcompilersettingsforFlashBuilderandFlashProfessionalare-as3=trueand-es=false.
Ifyouplantoextendanyofthecoreclassesandoverrideanymethods,youshouldunderstandhowtheAS3namespacecanaffecthowyoumustdeclareanoverriddenmethod.
IfyouareusingtheAS3namespace,anymethodoverrideofacoreclassmethodmustalsousetheAS3namespacealongwiththeoverrideattribute.
IfyouarenotusingtheAS3namespaceandwanttoredefineacoreclassmethodinasubclass,youshouldnotusetheAS3namespaceortheoverridekeyword.
Example:GeometricShapesTheGeometricShapessampleapplicationshowshowanumberofobject-orientedconceptsandfeaturescanbeappliedusingActionScript3.
0,including:DefiningclassesExtendingclassesPolymorphismandtheoverridekeywordDefining,extending,andimplementinginterfacesItalsoincludesa"factorymethod"thatcreatesclassinstances,showinghowtodeclareareturnvalueasaninstanceofaninterface,andusethatreturnedobjectinagenericway.
Togettheapplicationfilesforthissample,seewww.
adobe.
com/go/learn_programmingAS3samples_flash.
TheGeometricShapesapplicationfilescanbefoundinthefolderSamples/GeometricShapes.
Theapplicationconsistsofthefollowingfiles:116LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011DefiningtheGeometricShapesclassesTheGeometricShapesapplicationletstheuserspecifyatypeofgeometricshapeandasize.
Itthenrespondswithadescriptionoftheshape,itsarea,anddistancearounditsperimeter.
Theapplicationuserinterfaceistrivial,includingafewcontrolsforselectingthetypeofshape,settingthesize,anddisplayingthedescription.
Themostinterestingpartofthisapplicationisunderthesurface,inthestructureoftheclassesandinterfacesthemselves.
Thisapplicationdealswithgeometricshapes,butitdoesn'tdisplaythemgraphically.
TheclassesandinterfacesthatdefinethegeometricshapesinthisexampleareshowninthefollowingdiagramusingUnifiedModelingLanguage(UML)notation:FileDescriptionGeometricShapes.
mxmlorGeometricShapes.
flaThemainapplicationfileinFlash(FLA)orFlex(MXML).
com/example/programmingas3/geometricshapes/IGeometricShape.
asThebaseinterfacedefiningmethodstobeimplementedbyallGeometricShapesapplicationclasses.
com/example/programmingas3/geometricshapes/IPolygon.
asAninterfacedefiningmethodstobeimplementedbyGeometricShapesapplicationclassesthathavemultiplesides.
com/example/programmingas3/geometricshapes/RegularPolygon.
asAtypeofgeometricshapethathassidesofequallengthpostponedsymmetricallyaroundtheshape'scenter.
com/example/programmingas3/geometricshapes/Circle.
asAtypeofgeometricshapethatdefinesacircle.
com/example/programmingas3/geometricshapes/EquilateralTriangle.
asAsubclassofRegularPolygonthatdefinesatrianglewithallsidesthesamelength.
com/example/programmingas3/geometricshapes/Square.
asAsubclassofRegularPolygondefiningarectanglewithallfoursidesthesamelength.
com/example/programmingas3/geometricshapes/GeometricShapeFactory.
asAclasscontainingafactorymethodforcreatingshapesgivenashapetypeandsize.
117LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011GeometricShapesExampleClassesDefiningcommonbehaviorwithinterfacesThisGeometricShapesapplicationdealswiththreetypesofshapes:circles,squares,andequilateraltriangles.
TheGeometricShapesclassstructurebeginswithaverysimpleinterface,IGeometricShape,thatlistsmethodscommontoallthreetypesofshapes:packagecom.
example.
programmingas3.
geometricshapes{publicinterfaceIGeometricShape{functiongetArea():Number;functiondescribe():String;}}Theinterfacedefinestwomethods:thegetArea()method,whichcalculatesandreturnstheareaoftheshape,andthedescribe()method,whichassemblesatextdescriptionoftheshape'sproperties.
It'salsodesirabletoknowthedistancearoundtheperimeterofeachshape.
However,theperimeterofacircleiscalledthecircumference,andit'scalculatedinauniqueway,sothebehaviordivergesfromthatofatriangleorasquare.
Stillthereisenoughsimilaritybetweentriangles,squares,andotherpolygonsthatitmakessensetodefineanewinterfaceclassjustforthem:IPolygon.
TheIPolygoninterfaceisalsorathersimple,asshownhere:packagecom.
example.
programmingas3.
geometricshapes{publicinterfaceIPolygonextendsIGeometricShape{functiongetPerimeter():Number;functiongetSumOfAngles():Number;}}>IGeometricShape+getArea():Number+describe():String>IPolygon+getPerimeter():Number+getSumOfAngles():NumberCircle+diameter:Number+Circle():Circle+getArea():Number+describe():String+getCircumference():Number+numSides:int+sideLength:Number+RegularPolygon():RegularPolygon+getSumOfAngles():Number+getPerimeter():Number+getArea():Number+describe():StringRegularPolygon+EquilateralTriangle():EquilateralTriangle+getArea():Number+describe():StringEquilateralTriangle+Square():Square+getArea():Number+describe():StringSquare118LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011Thisinterfacedefinestwomethodscommontoallpolygons:thegetPerimeter()methodthatmeasuresthecombineddistanceofallthesides,andthegetSumOfAngles()methodthataddsupalltheinteriorangles.
TheIPolygoninterfaceextendstheIGeometricShapeinterface,whichmeansthatanyclassthatimplementstheIPolygoninterfacemustdeclareallfourmethods—thetwofromtheIGeometricShapeinterface,andthetwofromtheIPolygoninterface.
DefiningtheshapeclassesOnceyouhaveagoodideaaboutthemethodscommontoeachtypeofshape,youcandefinetheshapeclassesthemselves.
Intermsofhowmanymethodsyouneedtoimplement,thesimplestshapeistheCircleclass,shownhere:packagecom.
example.
programmingas3.
geometricshapes{publicclassCircleimplementsIGeometricShape{publicvardiameter:Number;publicfunctionCircle(diam:Number=100):void{this.
diameter=diam;}publicfunctiongetArea():Number{//TheformulaisPi*radius*radius.
varradius:Number=diameter/2;returnMath.
PI*radius*radius;}publicfunctiongetCircumference():Number{//TheformulaisPi*diameter.
returnMath.
PI*diameter;}publicfunctiondescribe():String{vardesc:String="ThisshapeisaCircle.
\n";desc+="Itsdiameteris"+diameter+"pixels.
\n";desc+="Itsareais"+getArea()+".
\n";desc+="Itscircumferenceis"+getCircumference()+".
\n";returndesc;}}}TheCircleclassimplementstheIGeometricShapeinterface,soitmustprovidecodeforboththegetArea()methodandthedescribe()method.
Inaddition,itdefinesthegetCircumference()method,whichisuniquetotheCircleclass.
TheCircleclassalsodeclaresaproperty,diameter,whichwon'tbefoundintheotherpolygonclasses.
Theothertwotypesofshapes,squaresandequilateraltriangles,havesomeotherthingsincommon:theyeachhavesidesofequallength,andtherearecommonformulasyoucanusetocalculatetheperimeterandsumofinterioranglesforboth.
Infact,thosecommonformulasapplytoanyotherregularpolygonsthatyoudefineinthefutureaswell.
119LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011TheRegularPolygonclassisthesuperclassforboththeSquareclassandtheEquilateralTriangleclass.
Asuperclassletsyoudefinecommonmethodsinoneplace,soyoudon'thavetodefinethemseparatelyineachsubclass.
HereisthecodefortheRegularPolygonclass:packagecom.
example.
programmingas3.
geometricshapes{publicclassRegularPolygonimplementsIPolygon{publicvarnumSides:int;publicvarsideLength:Number;publicfunctionRegularPolygon(len:Number=100,sides:int=3):void{this.
sideLength=len;this.
numSides=sides;}publicfunctiongetArea():Number{//Thismethodshouldbeoverriddeninsubclasses.
return0;}publicfunctiongetPerimeter():Number{returnsideLength*numSides;}publicfunctiongetSumOfAngles():Number{if(numSides>=3){return((numSides-2)*180);}else{return0;}}publicfunctiondescribe():String{vardesc:String="Eachsideis"+sideLength+"pixelslong.
\n";desc+="Itsareais"+getArea()+"pixelssquare.
\n";desc+="Itsperimeteris"+getPerimeter()+"pixelslong.
\n";desc+="Thesumofallinterioranglesinthisshapeis"+getSumOfAngles()+"degrees.
\n";returndesc;}}}First,theRegularPolygonclassdeclarestwopropertiesthatarecommontoallregularpolygons:thelengthofeachside(thesideLengthproperty)andthenumberofsides(thenumSidesproperty).
TheRegularPolygonclassimplementstheIPolygoninterfaceanddeclaresallfouroftheIPolygoninterfacemethods.
Itimplementstwoofthese—thegetPerimeter()andgetSumOfAngles()methods—usingcommonformulas.
120LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011BecausetheformulaforthegetArea()methoddiffersfromshapetoshape,thebaseclassversionofthemethodcannotincludecommonlogicthatcanbeinheritedbythesubclassmethods.
Instead,itsimplyreturnsa0defaultvaluetoindicatethattheareawasnotcalculated.
Tocalculatetheareaofeachshapecorrectly,thesubclassesoftheRegularPolygonclasshavetooverridethegetArea()methodthemselves.
ThefollowingcodefortheEquilateralTriangleclassshowhowthegetArea()methodisoverridden:packagecom.
example.
programmingas3.
geometricshapes{publicclassEquilateralTriangleextendsRegularPolygon{publicfunctionEquilateralTriangle(len:Number=100):void{super(len,3);}publicoverridefunctiongetArea():Number{//Theformulais((sideLengthsquared)*(squarerootof3))/4.
return((this.
sideLength*this.
sideLength)*Math.
sqrt(3))/4;}publicoverridefunctiondescribe():String{/*startswiththenameoftheshape,thendelegatestherestofthedescriptionworktotheRegularPolygonsuperclass*/vardesc:String="ThisshapeisanequilateralTriangle.
\n";desc+=super.
describe();returndesc;}}}TheoverridekeywordindicatesthattheEquilateralTriangle.
getArea()methodintentionallyoverridesthegetArea()methodfromtheRegularPolygonsuperclass.
WhentheEquilateralTriangle.
getArea()methodiscalled,itcalculatestheareausingtheformulaintheprecedingcode,andthecodeintheRegularPolygon.
getArea()methodneverexecutes.
Incontrast,theEquilateralTriangleclassdoesn'tdefineitsownversionofthegetPerimeter()method.
WhentheEquilateralTriangle.
getPerimeter()methodiscalled,thecallgoesuptheinheritancechainandexecutesthecodeinthegetPerimeter()methodoftheRegularPolygonsuperclass.
TheEquilateralTriangle()constructorusesthesuper()statementtoexplicitlyinvoketheRegularPolygon()constructorofitssuperclass.
Ifbothconstructorshadthesamesetofparameters,youcouldhaveomittedtheEquilateralTriangle()constructorcompletely,andtheRegularPolygon()constructorwouldbeexecutedinstead.
However,theRegularPolygon()constructorneedsanextraparameter,numSides.
SotheEquilateralTriangle()constructorcallssuper(len,3),whichpassesalongtheleninputparameterandthevalue3toindicatethatthetrianglehasthreesides.
Thedescribe()methodalsousesthesuper()statement,butinadifferentway.
ItusesittoinvoketheRegularPolygonsuperclass'versionofthedescribe()method.
TheEquilateralTriangle.
describe()methodfirstsetsthedescstringvariabletoastatementaboutthetypeofshape.
ThenitgetstheresultsoftheRegularPolygon.
describe()methodbycallingsuper.
describe(),anditappendsthatresulttothedescstring.
TheSquareclassisn'tdescribedindetailhere,butitissimilartotheEquilateralTriangleclass,providingaconstructoranditsownimplementationsofthegetArea()anddescribe()methods.
121LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011PolymorphismandthefactorymethodAsetofclassesthatmakegooduseofinterfacesandinheritancecanbeusedinmanyinterestingways.
Forexample,alloftheshapeclassesdescribedsofareitherimplementtheIGeometricShapeinterfaceorextendasuperclassthatdoes.
SoifyoudefineavariabletobeaninstanceofIGeometricShape,youdon'thavetoknowwhetheritisactuallyaninstanceoftheCircleortheSquareclasstocallitsdescribe()method.
Thefollowingcodeshowshowthisworks:varmyShape:IGeometricShape=newCircle(100);trace(myShape.
describe());WhenmyShape.
describe()iscalled,itexecutesthemethodCircle.
describe(),becauseeventhoughthevariableisdefinedasaninstanceoftheIGeometricShapeinterface,Circleisitsunderlyingclass.
Thisexampleshowstheprincipleofpolymorphisminaction:theexactsamemethodcallresultsindifferentcodebeingexecuted,dependingontheclassoftheobjectwhosemethodisbeinginvoked.
TheGeometricShapesapplicationappliesthiskindofinterface-basedpolymorphismusingasimplifiedversionofadesignpatternknownasthefactorymethod.
Thetermfactorymethodmeansafunctionthatreturnsanobjectwhoseunderlyingdatatypeorcontentscandifferdependingonthecontext.
TheGeometricShapeFactoryclassshownheredefinesafactorymethodnamedcreateShape():packagecom.
example.
programmingas3.
geometricshapes{publicclassGeometricShapeFactory{publicstaticvarcurrentShape:IGeometricShape;publicstaticfunctioncreateShape(shapeName:String,len:Number):IGeometricShape{switch(shapeName){case"Triangle":returnnewEquilateralTriangle(len);case"Square":returnnewSquare(len);case"Circle":returnnewCircle(len);}returnnull;}publicstaticfunctiondescribeShape(shapeType:String,shapeSize:Number):String{GeometricShapeFactory.
currentShape=GeometricShapeFactory.
createShape(shapeType,shapeSize);returnGeometricShapeFactory.
currentShape.
describe();}}}122LEARNINGACTIONSCRIPT3.
0Object-orientedprogramminginActionScriptLastupdated5/2/2011ThecreateShape()factorymethodletstheshapesubclassconstructorsdefinethedetailsoftheinstancesthattheycreate,whilereturningthenewobjectsasIGeometricShapeinstancessothattheycanbehandledbytheapplicationinamoregeneralway.
ThedescribeShape()methodintheprecedingexampleshowshowanapplicationcanusethefactorymethodtogetagenericreferencetoamorespecificobject.
TheapplicationcangetthedescriptionforanewlycreatedCircleobjectlikethis:GeometricShapeFactory.
describeShape("Circle",100);ThedescribeShape()methodthencallsthecreateShape()factorymethodwiththesameparameters,storingthenewCircleobjectinastaticvariablenamedcurrentShape,whichwastypedasanIGeometricShapeobject.
Next,thedescribe()methodiscalledonthecurrentShapeobject,andthatcallisautomaticallyresolvedtoexecutetheCircle.
describe()method,returningadetaileddescriptionofthecircle.
EnhancingthesampleapplicationTherealpowerofinterfacesandinheritancebecomesapparentwhenyouenhanceorchangeyourapplication.
Saythatyouwantedtoaddanewshape,apentagon,tothissampleapplication.
YouwouldcreateaPentagonclassthatextendstheRegularPolygonclassanddefinesitsownversionsofthegetArea()anddescribe()methods.
ThenyouwouldaddanewPentagonoptiontothecomboboxintheapplication'suserinterface.
Butthat'sit.
ThePentagonclasswouldautomaticallygetthefunctionalityofthegetPerimeter()methodandthegetSumOfAngles()methodfromtheRegularPolygonclassbyinheritance.
BecauseitinheritsfromaclassthatimplementstheIGeometricShapeinterface,aPentagoninstancecanbetreatedasanIGeometricShapeinstancetoo.
Thatmeansthattoaddanewtypeofshape,youdonotneedtochangethemethodsignatureofanyofthemethodsintheGeometricShapeFactoryclass(andconsequently,youdon'tneedtochangeanyofthecodethatusestheGeometricShapeFactoryclasseither).
YoumaywanttoaddaPentagonclasstotheGeometricShapesexampleasanexercise,toseehowinterfacesandinheritancecaneasetheworkloadofaddingnewfeaturestoanapplication.

特网云(198元/月),高质量云虚拟主机低至0.16元/天,裸金属服务器仅需10.5元/天

特网云为您提供高速、稳定、安全、弹性的云计算服务计算、存储、监控、安全,完善的云产品满足您的一切所需,深耕云计算领域10余年;我们拥有前沿的核心技术,始终致力于为政府机构、企业组织和个人开发者提供稳定、安全、可靠、高性价比的云计算产品与服务。官方网站:https://www.56dr.com/ 10年老品牌 值得信赖 有需要的请联系======================特网云推出多IP云主机...

云如故枣庄高防(49元)大内存2H2G49元8H8G109元

云如故是一家成立于2018年的国内企业IDC服务商,由山东云如故网络科技有限公司运营,IDC ICP ISP CDN VPN IRCS等证件齐全!合法运营销售,主要从事自营高防独立服务器、物理机、VPS、云服务器,虚拟主机等产品销售,适合高防稳定等需求的用户,可用于建站、游戏、商城、steam、APP、小程序、软件、资料存储等等各种个人及企业级用途。机房可封UDP 海外 支持策略定制 双层硬件(傲...

Vultr新注册赠送100美元活动截止月底 需要可免费享30天福利

昨天晚上有收到VULTR服务商的邮件,如果我们有清楚的朋友应该知道VULTR对于新注册用户已经这两年的促销活动是有赠送100美元最高余额,不过这个余额有效期是30天,如果我们到期未使用完的话也会失效的。但是对于我们一般用户来说,这个活动还是不错的,只需要注册新账户充值10美金激活账户就可以。而且我们自己充值的余额还是可以继续使用且无有效期的。如果我们有需要申请的话可以参考"2021年最新可用Vul...

adobe flash player 10 3为你推荐
雅虎社区雅虎资讯在哪里提交无线路由器限速设置无线路由器能设置限速吗?或者说那个牌子的能。spgnuxPC操作系统如何描述不兼容安卓手机软件不兼容怎么办?镜像文件是什么什么是文件镜像?什么是镜像文件?苹果5怎么越狱苹果5怎么越狱xp系统停止服务xp系统停止服务怎么办bt封杀现在是全面封杀BT下载了吗?现在都找不到BT下载影片了iphone6上市时间苹果六什么时候出的如何快速收录如何做到让百度快速收录
最新代理服务器地址 stablehost 狗爹 秒解服务器 国内永久免费云服务器 idc测评网 paypal认证 北京主机 linux空间 100m空间 爱奇艺vip免费试用7天 昆明蜗牛家 购买国外空间 超级服务器 国外视频网站有哪些 web服务器搭建 国外在线代理服务器 石家庄服务器托管 德讯 中国联通宽带测试 更多