Strong Datatypes for Properties

 <  Day Day Up  >  

The flaw we find in Figure 3.3 is that it is not adding the two numbers ; instead, it is concatenating them. In ActionScript 2.0, as well as several other languages, the + operator is overloaded . This means it will perform different operations, based on the types of data on which it is acting; when acting on numbers, it will add them, when acting on strings, it will concatenate them.


As is standard in programming parlance, concatenating is the act of joining two strings to make a new single string. For more details on operators in ActionScript, see Macromedia Flash MX 2004 Advanced Training from the Source , by Derek Franklin and Jobe Makar.

As we learned in Chapter 1, "What's New in ActionScript 2.0?," ActionScript 2.0 is a strongly typed language. This means that when Flash determines what type of data a variable (or property) will hold, it won't accept other types of data, unless specifically instructed to do so. The text property of a text field is typed as a String object. Therefore, when Flash was instructed to show the results of the following:

 input1.text + input2.text; 

it took the string entered in the first box and concatenated it with the string in the second. If we truly want Flash to add the numbers instead of concatenating them, we will need to cast them to the proper datatype. Casting is how we instruct Flash to change the datatype of an object. If we want to cast a string as a number, we use the built-in Number() function. Equally, if we wanted to cast a number as a String object, we could use the String() function. Listing 3.1 shows the onRelease handler for the button rewritten to properly add the numbers that have been input.

Listing 3.1. The Addition Tool Now Shows the Expected Results
 btAdd.onRelease = function(){       var theTotal:Number = Number(input1.text)+Number(input2.text);       total.text = String(theTotal); } 

Here, we can see that we are explicitly casting the input from the text fields to numbers so that Flash can add them properly. We also need to cast the resulting number back to a string, as the text property of a text field is built to accept only strings. Figure 3.4 shows the full code, Stage, and results with the proper casting.

Figure 3.4. The Addition tool working properly with the help of casting.



The first four lines of ActionScript 2.0 shown in Figure 3.4 are declaring the datatypes of the visual objects on the Stage. Although this is optional, it helps the Flash compiler force the datatype checking within the application, and it also enables code hinting.

 <  Day Day Up  >  

Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162 © 2008-2017.
If you may any questions please contact us: