Unit-II Action Script I
Unit-II Action Script I
Action Script I
1
ActionScript 2.0 Features
ActionScript 2.0 adds relatively little new runtime
functionality to the language but radically
improves object-oriented development in Flash
by formalizing objected-oriented programming
(OOP) syntax and methodology.
2
Key ActionScript 2.0 Features introduced are:
The class statement, used to create formal classes.
The extends keyword, used to establish inheritance.
The interface statement, used to create Java-style
interfaces (i.e., abstract data types).
Classes provide implementations for interfaces using the
implements keyword. ActionScript 1.0 did not support
interfaces.
The official file extension for class files is .as.
Formerly, classes could be defined in timeline code or
in external .as files.
Class files can be edited in Flash MX Professional 2004 's
script editor or in an external text editor.
3
Key ActionScript 2.0 Features introduced are:
(contd...)
Formal method-definition syntax, used to create instance
methods and class methods in a class body. In ActionScript
1.0, methods were added to a class via the class
constructor's prototype property.
Formal getter and setter method syntax, which replaces
ActionScript 1.0's
Formal property-definition syntax, used to create instance
properties and class properties in a class body. In
ActionScript 1.0, instance properties could be added in
several ways—via the class constructor's prototype property,
in the constructor function, or on each object directly.
The private and public keywords, used to prevent certain
methods and properties from being accessed outside of a
class. 4
Key ActionScript 2.0 Features introduced are:
(contd...)
Static typing for variables, properties, parameters and return
values used to declare the datatype for each item
Type casting, used to tell the compiler to treat an object as
though it were an instance of another datatype, as is
sometimes required when using static typing.
Classpaths, used to define the location of one or more central
class repositories. This allows classes to be reused across
projects and helps make source files easy to manage.
Exception handling —including the throw and try/catch/finally
statements—used to generate and respond to program
errors.
Easy linking between movie clip symbols and ActionScript
2.0
classes via the symbol Linkage properties.
5
Features Introduced by Flash Player 7
14
Key Object-Oriented Prog. Concepts (Contd…)
Datatypes
15
Key Object-Oriented Prog. Concepts (Contd…)
Inheritance
Allow one class to adopt the method and property definitions of
another
Many classes can reuse the features of a single class
For example, specific Car, Boat, and Plane classes could reuse
the features of a generic Vehicle class, thus reducing
redundancy in the application
A class that inherits properties and methods from another
class is called a subclass.
The class from which a subclass inherits properties and
methods is called the subclass's superclass.
Naturally, a subclass can define its own properties and
methods in addition to those it inherits from its superclass.
16
Key Object-Oriented Prog. Concepts (Contd…)
Packages
we can create packages to contain groups of classes. A
package lets us organize classes into logical groups and
prevents naming conflicts between classes.
COMPILATION
When an OOP application is exported as a Flash movie
(i.e., a
.swf file), each class is compiled; that is, the compiler attempts
to convert each class from source code to bytecode—
instructions that the Flash Player can understand and execute.
If a class contains errors, compilation fails and the Flash
compiler displays the errors in the Output panel in the Flash
authoring tool.
Even if the movie compiles successfully, errors may still occur
while a program is running; these are called runtime errors17
Key Object-Oriented Prog. Concepts (Contd…)
Starting an Objected-Oriented Application
18
HOW TO APPLY OOP
Flash supports both procedural and object-oriented
programming and allows you to combine both approaches
in a single Flash movie.
The fundamental organizing structure of a Flash document
(a .fla file) is the timeline , which contains one or more
frames.
Each frame defines the content that is displayed on the
graphical canvas called the Stage.
In the Flash Player, frames are displayed one at a time in a
linear sequence, producing an animated effect—exactly like
the frames in a filmstrip.
Timeline-based project containing predetermined animated
sequences
19
Consider using OOP when creating:
Traditional desktop-style applications with few transitions
and standardized user interfaces
Applications that include server-side logic
Functionality that is reused across multiple projects
Components
Games
Highly customized user interfaces that include complex
visual transitions
20
Consider using procedural programming when creating:
Animations with small scripts that control flow or basic
interactivity
Simple applications such as a one-page product order
form or a newsletter subscription form
Highly customized user interfaces that include complex
visual transitions
21
Introduction : Datatypes and Type Checking
ActionScript 2.0 defines a wide variety of datatypes.
Some datatypes are native to the language itself (e.g.,
String, Number, and Boolean).
Others are included in the Flash Player and are available
throughout all Flash movies (e.g., Color, Date, and
TextField).
Still other datatypes are defined by components that can be
added individually to Flash movies (e.g., List, RadioButton,
and ScrollPane).
ActionScript 2.0 belongs to a datatype, whether built-in or
programmer-defined.
Ex. MovieClip class getTime( ), gotoAndPlay( ).
22
Introduction: Datatypes and Type Checking (Contd..)
var today;
today = new Date( ).getDay( );
// Sunday is 0, Monday is 1, ... Friday is 5.
if (today == 5) {
trace("Looking forward to the
weekend!");
}
To help us recognize and isolate datatype-related problems
in our code, we use ActionScript 2.0's type checking
capabilities.
ActionScript 2.0 requires that you formally declare the
return
datatypevalue that you
of every want checked.
variable, property, parameter, and
23
Introduction: Datatypes and Type Checking (Contd..)
To declare the datatype of a variable or property, we use this
general form, referred to as post-colon syntax:
var variableOrPropertyName:datatype
var count:Number;
ActionScript 2.0 performs type checking on every variable,
property, parameter, and return value that has a declared
datatype.
var today;
today = new Date( ).getDay( );
The preceding code simply stores the return value of
getDay( )
today stores
into today. a number,
Because not avalue
the return string.
of getDay( ) is a
number, 24
Introduction: Datatypes and Type Checking (Contd..)
Fixing a datatype mismatch error
var today:Number
today = new Date( ).getDay( );
// Sunday is 0, Monday is 1, ... Friday is 5.
if (today == 5) {
trace("Looking forward to the
weekend!"); }
One way to derive a string from a
number
var today:Number = new
Date( ).getDay( );
var dayNames:Array = ["Sunday", "Monday", "Tuesday",
"Wednesday", “Thursday", “Friday", "Saturday"];
var todayName:String = dayNames[today]; 25
currentDay_txt.text = todayName;
Introduction: Datatypes and Type Checking (Contd..)
ActionScript 2.0's approach to datatyping is called static
typing .
In static typing, the datatype of variables and other data
containers is fixed at compile time so that the compiler can
guarantee the validity of every method called and property
accessed in the program.
The converse of static typing is dynamic typing , in which
each value is associated with a datatype at runtime, not at
compile time.
With dynamic typing, data containers such as variables can
change datatypes at runtime because type information is
associated with each value, not with each data container
26
Why Static Typing?
If a type mismatch error occurs, a program may be
able to run, but it wouldn't likely be able to perform
one or more requested operations.
Such errors often lead to program failures. Some
compilers merely warn of type mismatch errors but still
allow compilation to continue.
However, ActionScript 2.0's static typing facilities
prevent the movie from compiling if type mismatch
errors exist.
Type checking guarantees the validity of most
operations at compile time, catching potential errors
before they ever occur. 27
Why Static Typing (Contd..)
Type checking reduces the amount of manual
data-verification code you need in your methods
Dynamic type checking is often less restrictive and
can make code easier to change than statically
typed code.
The main advantage of static type checking is that
it can check all your code at compile time, whereas
dynamic type checking requires that you execute
the code in order to verify it.
28
Type Syntax
ActionScript 2.0's compile-time type checking can
be applied to:
A variable
A property
A function or method parameter
A function or method return value
34
Compatible Types
A variable of one type can store only a value of a
compatible type.
A type, X, is compatible with another type, Y, if X is of type
Y, or if X is any subtype of Y.
Ex: class Ball and a subclass Basketball.
var ball1:Ball = new Basketball( );
// Legal!
Every Ball instance does not necessarily have the
properties and methods of the Basketball class. (Compile
time type mismatch error)
var ball2:Basketball = new Ball( ); 35
// Illegal!
Handling Any Datatype
In ActionScript 2.0, we can make a variable, property, parameter
or return value accept data of any type by specifying Object as
the datatype.
We declare the datatype of container as Object. We can
subsequently store an instance of any class in it without error.
var container:Object = new Date( ); // No error.
container = new Color( ); // No error.
This technique works because the Object class is the superclass
of all ActionScript classes, so all types are compatible with the
Object type
trace(container.toString( )); // Execute toString( ) normally.
container.blahblah( );// Invoke nonexistent method. No error.
toString( )method excutes, because it is supported by all objects.
36
Compatibility with null and undefined
AS 2.0 program store null or undefined in a variable as an
indication of an absence of data or an uninitialized variable.
var target:MovieClip = null; //
Legal. function square
(x:Number):Number { return x*x;
}
square(null); // Legal.
function square (x:Number):Number {
if (x == 0) {
return null; // Legal.
}
return x*x;
} 37
Compatibility with null and undefined (Contd..)
This flexibility allows us to use the null type to indicate an
empty value for any data container.
var tf:TextFormat = new TextFormat(null, null, null,
true);
Compatibility with undefined also allows ActionScript to assign
undefined to parameters, variables, and properties that have
never been assigned a value.
public function displayMsg (msg:String,
sentBy:String):Void {
// Use "Anonymous" if a name was not supplied.
if (sentBy == undefined) {
sentBy = "Anonymous"; }
// Display the message in a text field.
38
} output.text = sentBy + ": " + msg;
Built-in Dynamic Classes
To allow new properties and methods to be added to a class's
instances without generating a compile-time error
We can define your own dynamic classes, but some built-in
classes are dynamic by default.
Array, ContextMenu, ContextMenuItem, TextField,
Function,FunctionArguments ,LoadVars, MovieClip, Object
When we attempt to access a nonexistent property or method
on an object of one of the preceding dynamic classes, the
ActionScript 2.0 compiler does not generate an error.
var dataSender:LoadVars = new LoadVars( );
dataSender.firstName = "Rebecca"; //
No error (Type mismatch) var
list:Array = new Date( ); 39
Casting
Casting is used to tell the compiler the type of an object
when the compiler can’t determine the object types on
it’s own.
Syntax : Type(object);
Where object is the object to cast and Type is the
datatype.
E.g.: var obj:Object =new Object();
var tf:TextField = new TextField(obj);
Casting doesn’t convert an object from one class to
another. It tells the compiler to treat the object or datum as
though it were an instance of the specified datatype. It use
a cast to tell the compiler the type of an object .
40
Casting (Contd…)
var ship: EnemyShip =theEnemyManager.getClosestShip();
if(ship instanceof Bomber){
Bomber(ship).bomb (); // cast to bomber
}
else if(ship instanceof Cruiser)
{ Cruiser(ship).evade();
}
else if(ship instanceof Fighter)
{ Fighter(ship).callReinforcements();
Fighter(ship).fire();
} 41
Casting Terminology
Casting an object to one of its supertypes is known as
upcast.
E.g.: var bball:BasketBall =new BasketBall();
var genericball:Ball =new Ball(bball); // upcast bball
Casting an object one of its subtypes is known as downcast.
E.g.: var b:Ball =new Ball();
var bball:BasketBall =new BasketBall(b); // downcast of b
An upcast is safe and downcast is unsafe. Because
supertype is not necessarily be an instance of its
subtype.
E.g.: var ball1: Ball =new BasketBall(); // without casting
var ball1 : Ball=Ball(new BasketBall()); // safe upcast 42
Casting does not affect method or
Property selection
If a superclass define a method or property i.e., overhidden
by a subclass, casting does not affect which version of a
method or property to be used.
When an overridden method is invoked on an instance of a
subclass, the subclass version of the method is always used,
even if the subclass instance is cast to the superclass.
Casting versus Conversion
Casting merely tells the compiler to treat an object as
though it were an instance of the specified datatype.
Conversion does change an object from one datatype to
another.
43
Casting to String, Number, Boolean, Date & Array
The String(), Number(), Boolean() and Array() functions
perform data conversions
The Date() function returns the current time as a
string
Syntax: Number(value) // to convert a value to a
number
E.g: Var obj:Object=[1,2,3];
function output (msg:Object):Void {
// use typeof to detect the datatype of primitive values
if ( typeof msg==“string”) { trace(msg); }
// use Instanceof to check the class of an object
if (msg instanceof Array){
trace(msg.join(“\n”)); }} Output 44
49
Properties
Classes use properties to store information. But some
information relates to a class as a whole
Class properties
Named data containers associated with a class
Instance properties
Named data containers associated with objects (i.e.,
instances of the class)
Together, class properties and instance properties are
sometimes referred to as fixed properties
In ActionScript and ECMAScript 4, instance properties are
sometimes called instance variables, and class properties
are sometimes called class variables
50
Instance properties:
Are stored individually on each instance of a class
Are accessed through instances only
Can be set uniquely for one instance without affecting any
other instances
An instance property is declared once for the entire class,
but each instance of the class maintains its own value.
The general syntax is:
var propertyName:datatype = value;
If datatype is omitted, no type checking is performed on the
property
var propertyName = value;
// No type checking for this property.
51
Access control modifiers in AS, Java, & C++
Access control
ActionScript Java C++
modifier
No access No access No access
public
restrictions restrictions restrictions
private Class and subclass Class access only Class access only
access only
Access allowed
no modifier Same as public from class's own Same as private
package only
Access allowed
from class's own
Access allowed
package and
protected Not supported from class and
class's subclasses
subclass only
in any other
package 52
Compile-Time Constant Expressions
An instance property definition can assign a default value to a
property, provided that the value is a so-called compile-time
constant expression.
A compile-time constant expression is an expression whose
value can be fully determined at compile time. They include :
null, numeric, boolean, and string constants
The following operators (used only on numbers, booleans,
strings, null, or undefined): + (unary and binary), - (unary and
binary), ~, !, *, /, %, <<, >>, >>>, <, >, <=, >=, instanceof, ==,
!=, ===, !==, &, ^, |, &&, ^^, ||, and ?: (ternary operator)
Array literals, Object literals, and instances of the following
classes: Array, Boolean, Number, Object, and String
References to other compile-time constant expressions
Example: 4 + 5, “Hello" + " world", null, [4, 5], new Array(4, 5)
53
Methods
Methods are functions that determine the behavior of a class.
If a parameter's type is omitted in the method definition, no
type checking is performed for that parameter .
If returnType is omitted, no type checking is performed for
the return value.
A function with return type Void may not return a value.
54
Referring to the Current Object with the
Keyword this
Using this helps our class to remain encapsulated,
eliminating the need for the outside world to worry about the
object's internal requirements.
The this reference to the current object allows an object to
refer to itself without the need for an additional parameter, and
is therefore much cleaner.
Passing the current object to a method
The this keyword is most often used when passing the current
object to another object 's method
function someMethod ( ):Void {
// Pass this as a parameter to a completely separate object
someOtherObject.someOtherMethod(this); }
55
Garbage collection
When an object registers as a listener of another object, it
should always unregister itself before it is deleted.
This sloppiness can cause serious waste of memory. A class
should always provide a means of cleaning up stray object
references before an object is deleted.
ActionScript doesn't garbage-collect an object (i.e., free up the
memory used by an object) until no more references to it
remain. Cleanup is done in a custom die( ) or destroy( )
method that must be invoked before an object is deleted.
By providing a die( ) method, a class guarantees a safe means
of deleting its instances . .
56
Nesting Functions in Methods
ActionScript supports nested functions, which means
that functions can be declared within methods or even
within other functions.
A local variable, a nested function is accessible only to
its parent function (the function in which it is declared).
Code outside the parent function cannot execute the
nested function:
57
Accessing the current object from a
function nested in a method
A function nested in a method does not have direct access
to the current object (the object on which the method
was called).
The current object by storing a reference to it in a local
variable.
58
Getter and Setter Methods
To bridge the gap between the convenience of property
assignment and the safety of accessor methods, ActionScript
2.0 supports "getter" and "setter" methods.
Getter and setter methods are accessor-like methods,
defined within a class body, that are invoked automatically
when a developer tries to get or set a property directly.
function get propertyName ( ):returnType {
// getter methodstatements }
function set propertyName (newValue:type):Void {
// setter method
statements }
Getter and setter methods cannot be declared with the
private attribute.
When invoked getter and setter methods does not require use 59
60
Extra or Missing Arguments
Extra arguments are not (indeed cannot be) type checked
automatically by the compiler.
public function setWidth (w:Number):Void {
// If w is undefined, then quit
if (w == undefined) {
return; }
width = w;}
The arguments object
also stores:
A reference to the method currently executing
(arguments.callee)
A reference to the method that called the method
currently executing, if any (arguments.caller) 61
4.5 Constructor Functions (Take 2)
A constructor function is the metaphoric womb of a class; it
isn't responsible for creating new instances, but it can be
used to initialize each new instance.
When we create a new instance of a class using the new
operator, the class's constructor function runs. Within the
constructor function, we can customize the newly created
instance by setting its properties or invoking its methods.
class Box {
public function Box ( ) {
} }
To define a constructor function, we use the function
statement within a class body.
The constructor function's name must match its class's
name exactly (case sensitivity matters). 62
Constructor Functions (Take 2) (Contd…)
The constructor function's definition must not specify a
return type (not even Void).
The constructor function must not return a value
The constructor function's definition must not include the
static attribute, but it can be public or private.
ActionScript automatically provides a default constructor
that takes no parameters and performs no initialization on
new instances of the class.
A constructor function's parameter values are passed to it via
the new operator at object-creation time
.
new SomeClass(value1, value2,...valuen);
new Box(2, 3);
63
Simulating Multiple Constructor Functions
Unlike Java, ActionScript does not support multiple constructor
functions for a single class (overloaded constructors in Java).
64
overloaded constructors
65
Completing the Box Class
First decide whether the display elements will render themselves or be
rendered by a central class.
Decide how often the displayed elements should be updated—either
when some event occurs (such as a mouseclick) or repeatedly (as fast
as frames are displayed in the Flash Player).
Decide on the rendering technique. Each visual element in a Flash movie
must be displayed in a movie clip.
Decide on a screen refresh strategy.
66
A Box class complete with drawing routines
67
68
A Box class complete with drawing routines (Contd..)
69
Authoring An ActionScript 2.0 Class
Class Authoring Quick Start
To create an ActionScript 2.0 class, follow these general
steps:
Create a new text file with the .as extension using any
plain text editor or Flash MX Professional 2004's built-in
editor.
The .as file's name must match the class name
exactly
(case sensitivity matters).
Add the class definition to the .as file.
class NameOfClass {
// Class body goes here
}
To use an ActionScript 2.0 class in a Flash
movie, Steps:
1. Create a .fla file with any name, and place it in the same
folder as the .as file from Step 1 in the preceding procedure.
2. Optionally specify the class's export frame for the .fla file via
File Publish Settings Flash ActionScript Version Settings
Export Frame for Classes. This determines when the class
loads and when it becomes available in the movie. The export
frame is usually set to some frame after your movie's
preloader.
3. Use the class as desired throughout the .fla file, but after the
export frame specified in Step 2 (if any).
4. Export a .swf file using one of the following: File Publish,
Control Test Movie, or File Export Export Movie.
Designing the ImageViewer Class
With our ImageViewer class's name we have a list of
functionality that could be required of the ImageViewer class:
Load an image
Display an image
Crop an image to a particular rectangular "view region"
Display a border around the image
Display image load progress
Reposition the view region
Resize the view region
Pan (reposition) the image within the view region
Zoom (resize) the image within the view region
ImageViewer Implementation (Take 1)
To create the ImageViewer.as file using Flash MX
Professional 2004, follow these steps:
Choose File New.
In the New Document dialog box, on the General tab, for the
document Type, choose ActionScript File.
Click OK. The script editor launches with an empty file.
Choose File Save As.
In the Save As dialog box, specify ImageViewer.as as the
filename (using upper- and lowercase as shown) and save the
file in the imageviewer folder you created.
Notice that the class name, ImageViewer, and the filename,
ImageViewer.as, must match exactly (apart from the .as file
extension).
The ImageViewer class with constructor and
loadImage( ) method, properties (Take 1)
Using ImageViewer in a Movie
Find a (nonprogressive format) JPEG image on your system.
Name the JPEG image picture.jpg and place it in the same
folder as the ImageViewer.as file you created earlier.
Next we'll create a Flash document (.fla file) from which we'll
publish a Flash movie (.swf file) containing an instance of our
ImageViewer class.
For now, we'll place the .fla file, .as file, .swf file, and .jpg file
all in the same folder, making it easy for each file to access
the other files.
Create the Flash document that uses the ImageViewer class.
Follow these steps:
In the Flash authoring tool, choose File -> New.
In the New Document dialog box, on the General tab, for the
document Type, choose Flash Document, then click OK.
Using ImageViewer in a Movie (Contd…)
Use File -> Save As to save the Flash document as
imageViewer.fla in the same folder as the ImageViewer.as file.
In imageViewer.fla's main timeline, rename Layer 1 to scripts
Follow these steps to instantiate ImageViewer on frame 1 of
imageViewer.fla's main timeline:
Use Window -> Development Panels ->Actions (F9) to open
the Actions panel.
Select frame 1 in imageViewer.fla's main timeline.
Into the Actions panel, enter the following code:
imageDepth Class
The depth on which image_mc is created in container_mc
maskDepth Class
The depth on which mask_mc is created in container_mc
borderDepth Class
The depth on which border_mc is created in container_mc
borderThickness Instance
The thickness, in pixels, of the border around the image_mc clip
borderColor Instance
The integer RGB color of the border around the image_mc clip
The ImageViewer class, take 2
The ImageViewer class, take 2
The ImageViewer class, take 2
The ImageViewer class, take 2
•Now that our ImageViewer class can crop an image and add a border to it.
•When we used the first version of the ImageViewer class, we placed the
following code on frame 15 of imageViewer.fla: