keyword.22 Introduction to ActionScript 3.0Method closuresActionScript 3.0 enables a method closure to automatically remember its original objectinstance. This feature is useful for event handling. In ActionScript 2.0, method closureswould not remember what object instance they were extracted from, leading to unexpectedbehavior when the method closure was invoked. The mx.utils.Delegate class was a popularworkaround, but it is no longer needed.ECMAScript for XML (E4X)ActionScript 3.0 implements ECMAScript for XML (E4X), recently standardized as ECMA-357. E4X offers a natural, fluent set of language constructs for manipulating XML. Incontrast to traditional XML-parsing APIs, XML with E4X performs like a native data type ofthe language. E4X streamlines the development of applications that manipulate XML bydrastically reducing the amount of code needed. For more information about the ActionScript3.0 implementation of E4X, see Chapter 11, “Working with XML,” on page 343.To view ECMA’s E4X specification, go to www.ecma-international.org.Regular expressionsActionScript 3.0 includes native support for regular expressions so that you can quickly searchfor and manipulate strings. ActionScript 3.0 implements support for regular expressions asthey are defined in the ECMAScript (ECMA-262) edition 3 language specification.NamespacesNamespaces are similar to the traditional access specifiers used to control visibility ofdeclarations (public,private,protected). They work as custom access specifiers, whichcan have names of your choice. Namespaces are outfitted with a Universal Resource Identifier(URI) to avoid collisions, and are also used to represent XML namespaces when you workwith E4X.New primitive typesActionScript 2.0 has a single numeric type, Number, a double-precision, floating-pointnumber. ActionScript 3.0 contains the int and uint types. The int type is a 32-bit signedinteger that lets ActionScript code take advantage of the fast integer math capabilities of theCPU. The int type is useful for loop counters and variables where integers are used. The uinttype is an unsigned, 32-bit integer type that is useful for RGB color values, byte counts, andmore.What’s new in ActionScript 3.0 23Flash Player API featuresThe Flash Player API in ActionScript 3.0 contains many new classes that allow you to controlobjects at a low level. The architecture of the language is completely new and more intuitive.While there are too many new classes to cover in detail here, the following sections highlightsome significant changes.DOM3 event modelDocument Object Model Level 3 event model (DOM3) provides a standard way ofgenerating and handling event messages so that objects within applications can interact andcommunicate, maintaining their state and responding to change. Patterned after the WorldWide Web Consortium DOM Level 3 Events Specification, this model provides a clearer andmore efficient mechanism than the event systems available in previous versions ofActionScript.Events and error events are located in the flash.events package. The Flash componentsframework uses the same event model as the Flash Player API, so the event system is unifiedacross the Flash platform.Display list APIThe API for accessing the Flash Player display list—the tree that contains any visual elementsin a Flash application—consists of classes for working with visual primitives in Flash.The new Sprite class is a lightweight building block, similar to the MovieClip class but moreappropriate as a base class for UI components. The new Shape class represents raw vectorshapes. These classes can be instantiated naturally with thenewoperator and can bedynamically re-parented at any time.Depth management is now automatic and built into Flash Player, rendering assignment ofdepth numbers unnecessary. New methods are provided for specifying and managing the z-order of objects.Handling dynamic data and contentActionScript 3.0 contains mechanisms for loading and handling assets and data in your Flashapplication that are intuitive and consistent across the API. The new Loader class provides asingle mechanism for loading SWF files and image assets and provides a way to access detailedinformation about loaded content. The URLLoader

class provides a separate mechanism forloading text and binary data in data-driven applications. The Socket class provides a means toread and write binary data to server sockets in any format.24 Introduction to ActionScript 3.0Low-level data accessVarious APIs provide low-level access to data that was never before available in ActionScript.For data that is being downloaded, the URLStream class, which is implemented byURLLoader, provides access to data as raw binary data while it is being downloaded. TheByteArray class lets you optimize reading, writing, and working with binary data. The newSound API provides detailed control of sound through the SoundChannel and SoundMixerclasses. New APIs dealing with security provide information about the security privileges of aSWF file or loaded content, enabling you to better handle security errors.Working with textActionScript 3.0 contains a flash.text package for all text-related APIs. The TextLineMetricsclass provides detailed metrics for a line of text within a text field; it replaces theTextField.getLineMetrics()method in ActionScript 2.0. The TextField class contains anumber of interesting new low-level methods that can provide specific information about aline of text or a single character in a text field. These methods includegetCharBoundaries(), which returns a rectangle representing the bounding box of acharacter,getCharIndexAtPoint(), which returns the index of the character at a specifiedpoint, andgetFirstCharInParagraph(), which returns the index of the first character in aparagraph. Line-level methods includegetLineLength(), which returns the number ofcharacters in a specified line of text, andgetLineText(), which returns the text of thespecified line. A new Font class provides a means to manage embedded fonts in SWF files.Compatibility with previous versionsAs always, Flash Player provides full backward compatibility with previously publishedcontent. Any content that ran in previous versions of Flash Player runs in Flash Player 9. Theintroduction of ActionScript 3.0 in Flash Player 9, however, does present some challenges forinteroperability between old and new content running in Flash Player 9. The compatibilityissues include the following:■A single SWF file cannot combine ActionScript 1.0 or 2.0 code with ActionScript 3.0code.■ActionScript 3.0 code can load a SWF file written in ActionScript 1.0 or 2.0, but itcannot access the SWF file’s variables and functions.Compatibility with previous versions 25■SWF files written in ActionScript 1.0 or 2.0 cannot load SWF files written inActionScript 3.0. This means that SWF files authored in Flash 8 or Flex Builder 1.5 orearlier versions cannot load ActionScript 3.0 SWF files.The only exception to this rule is that an ActionScript 2.0 SWF file can replace itself withan ActionScript 3.0 SWF file, as long as the ActionScript 2.0 SWF file hasn't previouslyloaded anything into any of its levels. An ActionScript 2.0 SWF file can do this through acall toloadMovieNum(), passing a value of 0 to thelevelparameter.■In general, SWF files written in ActionScript 1.0 or 2.0 must be migrated if they are towork together with SWF files written in ActionScript 3.0. For example, say you created amedia player using ActionScript 2.0. The media player loads various content that was alsocreated using ActionScript 2.0. You cannot create new content in ActionScript 3.0 andload it in the media player. You must migrate the video player to ActionScript 3.0.If, however, you create a media player in ActionScript 3.0, that media player can performsimple loads of your ActionScript 2.0 content.26 Introduction to ActionScript 3.0The following table summarizes the limitations of previous versions of Flash Player in relationto loading new content and executing code, as well as the limitations for cross-scriptingbetween SWF files written in different versions of ActionScript.SupportedfunctionalityRun-time environmentFlash Player 7Flash Player 8Flash Player 9Can load SWFspublished for7 and earlier8 and earlier9 and earlierContains this AVMAVM1AVM1AVM1 and AVM2Runs SWFs written inActionScript1.0 and 2.01.0 and 2.01.0 and 2.0, and 3.0Supportedfunctionality** Content running in Flash Player 9 or later. Content running in Flash Player 8 or earlier canload, display, execute, and cross-script only ActionScript 1.0 and 2.0.Content created inActionScript 1.0 and 2.0ActionScript 3.0Can load content andexecute code in contentcreated inActionScript 1.0 and 2.0 onlyActionScript 1.0 and 2.0,and ActionScript 3.0Can cross script contentcreated inActionScript 1.0 and 2.0 only†† ActionScript 3.0 through Local Connection.ActionScript 3.0‡‡ ActionScript 1.0 and 2.0 through LocalConnection.272CHAPTER 2Getting started withActionScriptThis chapter is designed to get you started with ActionScript programming and give you thebackground you’ll need to understand the concepts and examples in the rest of this manual.We’ll begin with a discussion of basic programming concepts, described in the context of howto apply them in ActionScript. We’ll also cover the essentials of how to organize and build anActionScript application.ContentsProgramming fundamentals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Working with objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Common program elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42Example: Animation portfolio piece . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44Building applications with ActionScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Creating your own classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53Example: Creating a basic application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56Running subsequent examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63Programming fundamentalsSince ActionScript is a programming language, it will help you learn ActionScript if you firstunderstand a few general computer programming concepts.What computer programs doFirst of all, it’s useful to have a conceptual idea of what a computer program is and what itdoes. There are two main aspects to a computer program:■A program is a series of instructions or steps for the computer to carry out.■Each step ultimately involves manipulating some piece of information or data.28 Getting started with ActionScriptIn a general sense, a computer program is just a list of step-by-step instructions that you giveto the computer, which it performs one by one. Each individual instruction is known as astatement. As you’ll see throughout this manual, in ActionScript, each statement is writtenwith a semicolon at the end.In essence, all that a given instruction in a program does is manipulate some bit of data that’sstored in the computer’s memory. In a simple case, you might instruct the computer to addtwo numbers and store the result in its memory. In a more complex case, imagine there is arectangle drawn on the screen, and you want to write a program to move it somewhere else onthe screen. The computer is keeping track of certain information about the rectangle—the x,y coordinates where it’s located, how wide and tall it is, what color it is, and so forth. Each ofthose bits of information is stored somewhere in the computer’s memory. A program to movethe rectangle to a different location would have steps like “change the x coordinate to 200;change the y coordinate to 150” (in other words, specifying new values to be used for the xand y coordinates). Of course, the computer does something with this data to actually turnthose numbers into the image that appears on the computer screen; but for the level of detailwe’re interested in, it’s enough to know that the process of “moving a rectangle on the screen”really just involves changing bits of data in the computer’s memory.Variables and constantsSince programming mainly involves changing pieces of information in the computer’smemory, there needs to be a way to represent a single piece of information in the program. Avariable is a name that represents a value in the computer’s memory. As you write statementsto manipulate values, you write the variable’s name in place of the value; any time thecomputer sees the variable name in your program, it looks in its memory and uses the value itfinds there. For example, if you have two variables namedvalue1andvalue2, eachcontaining a number, to add those two numbers you could write the statement:value1 + value2When it’s actually carrying out the steps, the computer will look to see the values in eachvariable, and add them together.In ActionScript 3.0, a variable actually consists of three different parts:■The variable’s name■The type of data that can be stored in the variable■The actual value stored in the computer’s memoryProgramming fundamentals 29We’ve just discussed how the computer uses the name as a placeholder for the value. The datatype is also important. When you create a variable in ActionScript, you specify the specifictype of data that it will hold; from that point on, your program’s instructions can store onlythat type of data in the variable, and you can manipulate the value using the particularcharacteristics associated with its data type. In ActionScript, to create a variable (known asdeclaring the variable), you use thevarstatement:var value1:Number;In this case, we’ve told the computer to create a variable namedvalue1, which will hold onlyNumber data (“Number” is a specific data type defined in ActionScript). You can also store avalue in the variable right away:var value2:Number = 17;In the Adobe Flash CS3 Professional, there is another way to declare a variable. When youplace a movie clip symbol, button symbol, or text field on the Stage, you can give it aninstance name in the Property inspector. Behind the scenes, Flash creates a variable with thesame name as the instance name, which you can use in your ActionScript code to refer to thatStage item. So, for example, if you have a movie clip symbol on the Stage and you give it theinstance namerocketShip, whenever you use the variablerocketShipin your ActionScriptcode, you will in fact be manipulating that movie clip.Data typesIn ActionScript, there are many data types that you can use as the data type of the variablesyou create. Some of these can be thought of as “simple” or “fundamental” data types:■String: a textual value, like a name or the text of a book chapter■Numeric: ActionScript 3.0 includes three specific data types for numeric data:■Number: any numeric value, including values with or without a fraction■int: an integer (a whole number without a fraction)■uint: an “unsigned” integer, meaning a whole number that can’t be negative■Boolean: a true-or-false value, such as whether a switch is on or whether two values areequal30 Getting started with ActionScriptThe simple data types represent a single piece of information: for example, a single number ora single sequence of text. However, the majority of the data types defined in ActionScriptcould be described as complex data types, because they represent a set of values groupedtogether. For example, a variable with the data type Date represents a single value—a momentin time. Nevertheless, that date value is actually represented as several values: the day, month,year, hours, minutes, seconds, and so on, all of which are individual numbers. So while wethink of a date as a single value (and we can treat it as a single value by creating a Datevariable), internally the computer thinks of it as a group of several values that, put together,define a single date.Most of the built-in data types, as well as data types defined by programmers, are complexdata types. Some of the complex data types you might recognize are:■MovieClip: a movie clip symbol■TextField: a dynamic or input text field■SimpleButton: a button symbol■Date: information about a single moment in time (a date and time)Two words that are often used as synonyms for data type are class and object. A class is simplythe definition of a data type—it’s like a template for all objects of the data type, like saying “allvariables of the Example data type have these characteristics: A, B, and C.” An object, on theother hand, is just an actual instance of a class; a variable whose data type is MovieClip couldbe described as a MovieClip object. The following are different ways of saying the same thing:■The data type of the variablemyVariableis Number.■The variablemyVariableis a Number instance.■The variablemyVariableis a Number object.■The variablemyVariableis an instance of the Number class.Working with objects 31Working with objectsActionScript is what’s known as an object-oriented programming language. Object-orientedprogramming is simply an approach to programming—really nothing more than a way toorganize the code in a program, using objects.Earlier we defined a computer program as a series of steps or instructions that the computerperforms. Conceptually, then, we might imagine a computer program as just a single long listof instructions. However, in object-oriented programming, the program instructions aredivided among different objects—the code is grouped into chunks of functionality, so relatedtypes of functionality or related pieces of information are grouped together in one container.In fact, if you’ve worked with symbols in Flash, you’re already used to working with objects.Imagine you’ve defined a movie clip symbol—let’s say it’s a drawing of a rectangle—andyou’ve placed a copy of it on the Stage. That movie clip symbol is also (literally) an object inActionScript; it’s an instance of the MovieClip class.There are various characteristics of the movie clip that you can modify. For example, when it’sselected there are values you can change in the Property inspector, like its x coordinate, or itswidth, or various color adjustments like changing its alpha (transparency), or applying a drop-shadow filter to it. Other Flash tools let you make more changes, like using the FreeTransform tool to rotate the rectangle. All of these things that you can do to modify a movieclip symbol in the Flash authoring environment are also things you can do in ActionScript bychanging the pieces of data that are all put together into a single bundle called a MovieClipobject.In ActionScript object-oriented programming, there are three types of characteristics that anyclass can include:■Properties■Methods■EventsTogether, these elements are used to manage the pieces of data used by the program and todecide what actions are carried out and in what order.PropertiesA property represents one of the pieces of data that are bundled together in an object. A songobject might have properties namedartistandtitle; the MovieClip class has propertieslikerotation,x,width, andalpha. You work with properties like individual variables—infact, you might think of properties as simply the “child” variables contained in an object.32 Getting started with ActionScriptHere are some examples of ActionScript code that uses properties. This line of code moves theMovieClip namedsquareto the x coordinate 100 pixels:square.x = 100;This code uses the rotation property to make thesquareMovieClip rotate to match therotation of thetriangleMovieClip:square.rotation = triangle.rotation;This code alters the horizontal scale of thesquareMovieClip so that it’s one-and-a-half timeswider than it used to be:square.scaleX = 1.5;Notice the common structure: you use a variable (square,triangle) as the name of theobject, followed by a period (.) and then the name of the property (x,rotation,scaleX).The period, known as the dot operator, is used to indicate that you’re accessing one of the childelements of an object. The whole structure together, “variable name-dot-property name,” isused like a single variable, as a name for a single value in the computer’s memory.MethodsA method is an action that can be performed by an object. For example, if you’ve made amovie clip symbol in Flash with several keyframes and animation on its timeline, that movieclip can play, or stop, or be instructed to move the playhead to a particular frame.This code instructs the MovieClip namedshortFilmto start playing:shortFilm.play();This line makes the MovieClip namedshortFilmstop playing (the playhead stops in place,like pausing a video):shortFilm.stop();This code makes a MovieClip namedshortFilmmove its playhead to Frame 1 and stopplaying (like rewinding a video):shortFilm.gotoAndStop(1);Working with objects 33As you can see, methods, like properties, are accessed by writing the object’s name (a variable),then a period, and then the name of the method followed by parentheses. The parentheses arethe way that you indicate that you’re calling the method—or in other words, instructing theobject to perform that action. Sometimes values (or variables) are placed in the parentheses, asa way to pass along additional information that is needed to carry out the action. These valuesare known as method parameters. For example, thegotoAndStop()method needs to knowwhich frame it should go to, so it requires a single parameter in the parentheses. Othermethods, likeplay()andstop(), are self-explanatory, so they don’t require extrainformation. Nevertheless, they are still written with parentheses.Unlike properties (and variables), methods aren’t used as value placeholders. However, somemethods can perform calculations and return a result that can be used like a variable. Forexample, the Number class’stoString()method converts the numeric value to its textrepresentation:var numericData:Number = 9;var textData:String = numericData.toString();For instance, you would use thetoString()method if you wanted to display the value of aNumber variable in a text field on the screen. The TextField class’stextproperty (whichrepresents the actual text content displayed on the screen) is defined as a String, so it cancontain only text values. This line of code converts the numeric value in the variablenumericDatato text, and then makes it show up on the screen in the TextField object namedcalculatorDisplay:calculatorDisplay.text = numericData.toString();EventsWe’ve described a computer program as a series of instructions that the computer carries outstep-by-step. Some simple computer programs consist of nothing more than that—a few stepswhich the computer carries out, at which point the program ends. However, ActionScriptprograms are designed to keep running, waiting for user input or other things to happen.Events are the mechanism that determines which instructions the computer carries out andwhen.In essence, events are things that happen that ActionScript is aware of and can respond to.Many events are related to user interaction—like a user clicking a button, or pressing a key onthe keyboard—but there are also other types of events. For example, if you use ActionScript toload an external image, there is an event that can let you know when the image has finishedloading. In essence, when an ActionScript program is running, Adobe Flash Player just sitsand waits for certain things to happen, and when those things happen, it runs the specificActionScript code that you’ve specified for those events.34 Getting started with ActionScriptBasic event handlingThe technique for specifying certain actions that should be performed in response toparticular events is known as event handling. When you are writing ActionScript code toperform event handling, there are three important elements you’ll want to identify:■The event source: Which object is the one the event is going to happen to? For instance,which button will be clicked, or which Loader object is loading the image? The eventsource is also known as the event target, because it’s the object where the event is targetedby Flash Player (where the event actually happens).■The event: What is the thing that is going to happen, the thing that you want to respondto? This is important to identify, because many objects trigger several events.■The response: What step(s) do you want performed when the event happens?Any time you write ActionScript code to handle events, it will include these three elements,and the code will follow this basic structure (elements in bold are placeholders you’d fill in foryour specific case):function eventResponse(eventObject:EventType):void{// Actions performed in response to the event go here.}eventSource.addEventListener(EventType.EVENT_NAME, eventResponse);This code does two things. First, it defines a function, which is the way to specify the actionsyou want performed in response to the event. Next, it calls theaddEventListener()methodof the source object, in essence “subscribing” the function to the specified event so that whenthe event happens, the function’s actions are carried out. We’ll consider each of these parts inmore detail.A function provides a way for you to group actions together, with a single name that is like ashortcut name to carry out the actions. A function is identical to a method except that it isn’tnecessarily associated with a specific class (in fact, a method could be defined as a functionthat is associated with a particular class). When you’re creating a function for event handling,you must choose the name for the function (namedeventResponsein this case), and youmust also specify one parameter (namedeventObjectin this example). Specifying a functionparameter is like declaring a variable, so you also have to indicate the data type of theparameter. There is an ActionScript class defined for each event, and the data type you specifyfor the function parameter is always the class associated with the particular event you want torespond to. Finally, between the opening and closing curly braces ({...}), you write theinstructions you want the computer to carry out when the event happens.Working with objects 35Once you’ve written the event-handling function, you need to tell the event source object (theobject that the event happens to—for example, the button) that you want your function to becalled when the event happens. You do this by calling theaddEventListener()method ofthat object (all objects that have events also have anaddEventListener()method). TheaddEventListener()method takes two parameters:■First, the name of the specific event you want to respond to. Once again, each event isaffiliated with a specific class, and that class will have a special value predefined for eachevent—sort of like the event’s own unique name, which you should use for the firstparameter.■Second, the name of your event response function. Note that a function name is writtenwithout parentheses when it’s passed as a parameter.Examining the event-handling processThe following is a step-by-step description of the process that happens when you create anevent listener. In this case, it’s an example of creating a listener function that is called when anobject namedmyButtonis clicked.The actual code written by the programmer is as follows:function eventResponse(event:MouseEvent):void{// Actions performed in response to the event go here.}myButton.addEventListener(MouseEvent.CLICK, eventResponse);36 Getting started with ActionScriptHere is how this code would actually work when it’s running in Flash Player:1.When the SWF file loads, Flash Player makes note of the fact that there’s a function namedeventResponse().2.Flash Player then runs the code (specifically, the lines of code that aren’t in a function). Inthis case that’s only one line of code: calling theaddEventListener()method on theevent source object (namedmyButton) and passing theeventResponsefunction as aparameter.Working with objects 37a.Internally,myButtonhas a list of functions that are listening to each of its events, sowhen itsaddEventListener()method is called,myButtonstores theeventResponse()function in its list of event listeners.3.At some point, the user clicks themyButtonobject, triggering itsclickevent (identifiedasMouseEvent.CLICKin the code).At that point, the following occurs:38 Getting started with ActionScripta.Flash Player creates an object, an instance of the class associated with the event inquestion (MouseEvent in this example). For many events this will be an instance of theEvent class; for mouse events it will be a MouseEvent instance; and for other events itwill be an instance of the class that’s associated with that event. This object that’screated is known as the event object, and it contains specific information about theevent that happened: what type of event it is, where it happened, and other event-specific information if applicable.b.Flash Player then looks at the list of event listeners stored bymyButton. It goesthrough these functions one by one, calling each function and passing the event objectto the function as a parameter. Since theeventResponse()function is one ofmyButton’s listeners, as part of this process Flash Player calls theeventResponse()

function.Working with objects 39c.When theeventResponse()function is called, the code in that function runs, soyour specified actions are carried out.Event-handling examplesHere are a few more concrete examples of events to give you an idea of some of the commonevent elements and possible variations available when you write event-handling code:■Clicking a button to start the current movie clip playing. In the following example,playButtonis the instance name of the button, andthisis a special name meaning “thecurrent object”:this.stop();function playMovie(event:MouseEvent):void{this.play();}playButton.addEventListener(MouseEvent.CLICK, playMovie);■Detecting typing in a text field. In this example,entryTextis an input text field, andoutputTextis a dynamic text field:function updateOutput(event:TextEvent):void{var pressedKey:String = event.text;outputText.text = "You typed: " + pressedKey;}entryText.addEventListener(TextEvent.TEXT_INPUT, updateOutput);40 Getting started with ActionScript■Clicking a button to navigate to a URL. In this case,linkButtonis the instance name ofthe button:function gotoAdobeSite(event:MouseEvent):void{var adobeURL:URLRequest = new URLRequest("http://www.adobe.com/");navigateToURL(adobeURL);}linkButton.addEventListener(MouseEvent.CLICK, gotoAdobeSite);Creating object instancesOf course, before you can use an object in ActionScript, the object has to exist in the firstplace. One part of creating an object is declaring a variable; however, declaring a variable onlycreates an empty place in the computer’s memory. You must assign an actual value to thevariable—that is, create an object and store it in the variable—before you attempt to use ormanipulate it. The process of creating an object is known as instantiating the object—in otherwords, creating an instance of a particular class.One simple way to create an object instance doesn’t involve ActionScript at all. In Flash, whenyou place a movie clip symbol, button symbol, or text field on the Stage, and you assign it aninstance name in the Property inspector, Flash automatically declares a variable with thatinstance name, creates an object instance, and stores that object in the variable. Likewise, inAdobe Flex Builder when you create a component in Macromedia® MXML™ from Adobe(either by coding an MXML tag or by placing the component on the editor in Design mode)and assign an ID to that component (in the MXML markup or in the Flex Properties view),that ID becomes the name of an ActionScript variable, and an instance of the component iscreated and stored in the variable.However, you won’t always want to create an object visually. There are also several ways youcan create object instances using only ActionScript. First, with several ActionScript data types,you can create an instance using a literal expression—a value written directly into theActionScript code. Here are some examples:■Literal numeric value (enter the number directly):var someNumber:Number = 17.239;var someNegativeInteger:int = -53;var someUint:uint = 22;■Literal String value (surround the text with double quotation marks):var firstName:String = "George";var soliloquy:String = "To be or not to be, that is the question...";Working with objects 41■Literal Boolean value (use the literal valuestrueorfalse):var niceWeather:Boolean = true;var playingOutside:Boolean = false;■Literal XML value (enter the XML directly):var employee:XML = <employee><firstName>Harold</firstName><lastName>Webster</lastName></employee>;ActionScript also defines literal expressions for the Array, RegExp, Object, and Function datatypes. For details on these classes, see “Working with arrays” on page 223, “Using regularexpressions” on page 285, and “Object data type” on page 97.For any other data type, to create an object instance you use thenewoperator with the classname, like this:var raceCar:MovieClip = new MovieClip();var birthday:Date = new Date(2006, 7, 9);Creating an object using thenewoperator is often referred to as “calling the class’sconstructor.” A constructor is a special method that is called as part of the process of creatingan instance of a class. Notice that when you create an instance in this way, you put parenthesesafter the class name, and sometimes you specify parameter values—two things that you alsodo when calling a method.It’s important to be familiar with thenew ClassName()way of creating objects. If you needto create an instance of any ActionScript data type that doesn’t have a visual representation(and hence can’t be created by placing an item on the Flash Stage or the Design mode of FlexBuilder’s MXML editor), you can only do so by creating the object directly in ActionScriptusing thenewoperator.In Flash specifically, thenewoperator can also be used to create an instance of a movie clipsymbol that is defined in the Library but isn’t placed on the Stage. For more about this, see“Creating MovieClip objects with ActionScript” on page 498.NOTEEven for those data types that let you create instances using a literal expression, you canstill use thenewoperator to create an object instance. For instance, these two lines of