0% found this document useful (0 votes)
7K views

Unit-II Action Script I

ActionScript 2.0 introduced formal object-oriented programming features to Flash, including classes, inheritance using the extends keyword, interfaces, and public/private access modifiers. It also added static typing, exceptions, and other features. Flash Player 7 introduced new classes like MovieClipLoader and support for things like mouse wheel, printing, and CSS styling of text. Object-oriented programming organizes code into self-contained objects that encapsulate data and behavior via classes, objects, and methods.

Uploaded by

DHANASEKAR G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7K views

Unit-II Action Script I

ActionScript 2.0 introduced formal object-oriented programming features to Flash, including classes, inheritance using the extends keyword, interfaces, and public/private access modifiers. It also added static typing, exceptions, and other features. Flash Player 7 introduced new classes like MovieClipLoader and support for things like mouse wheel, printing, and CSS styling of text. Object-oriented programming organizes code into self-contained objects that encapsulate data and behavior via classes, objects, and methods.

Uploaded by

DHANASEKAR G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Unit II

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.

 ActionScript 2.0 provides a class keyword for


creating classes and an extends keyword for
establishing inheritance. Those keywords were
absent from ActionScript 1.0

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

 In addition to the ActionScript 2.0 language enhancements,


Flash Player 7 introduces some important new classes and
capabilities. They are:
 New array-sorting capabilities
 The ContextMenu and ContextMenuItem classes for
customizing the Flash Player context menu
 ID3 v2 tag support for loaded MP3 files
 Mouse wheel support in text fields ( Windows only)
 Improved MovieClip depth management methods
 The MovieClipLoader class for loading movie clips and
images
6
Features Introduced by Flash Player 7 (Contd…)

 The PrintJob class for printing with greater control than


was previously possible
 Support for images in text fields, including flowing text
around images
 Improved text metrics (the ability to obtain more accurate
measurements of the text in a text field than was possible
in Flash Player 6)
 Cascading stylesheet (CSS) support for text fields, allowing
the text in a movie to be formatted with a standard CSS
stylesheet
 Improved ActionScript runtime performance
 Strict case sensitivity
7
Object Oriented ActionScript
Procedural Programming & Object-Oriented Programming
 Traditional programming consists of various instructions
grouped into procedures.
 Procedures perform a specific task without any knowledge
of or concern for the larger program.
 In a procedural-style Flash program, repeated tasks are
stored in functions and data is stored in variables.
 The program runs by executing functions and changing
variable values, typically for the purpose of handling input
and generating output.
 Procedural programming is sensible for certain
applications; however, as applications become larger or
more complex and the interactions between procedures
 They can be hard to maintain, debug, and upgrade.
8
Procedural Prog. & Object-Oriented Prog. (Contd…)
 OOP is designed to make complex applications more
manageable by breaking them down into self-contained,
interacting modules.
 OOP lets us translate abstract concepts and tangible real-
world things into corresponding parts of a program
 OOP adds a level of conceptual organization to a
program.
 It groups related functions and variables together into separate
classes , each of which is a self-contained part of the program
with its own responsibilities.
 Classes are used to create individual objects that execute
functions and set variables on one another, producing the
program's behavior.
 Organizing the code into classes makes it easier to create a
program that maps well to real-world problems with real-world
9
components
Key Object-Oriented Programming Concepts
 An object is a self-contained software module that
contains related functions (called its methods ) and
variables (called its properties).
 Individual objects are created from classes, which
provide the blueprint for an object's methods and
properties
 A single class can be used to generate any number of
objects, each with the same general structure
 To build an object-oriented program:
 Create one or more classes.
 Make (i.e., instantiate) objects from those classes.
 Tell the objects what to do.
10
Key Object-Oriented Prog. Concepts (Contd…)
 We create, a Class Syntax
program can use class SpaceShip {
any of the classes public var speed:Number;
built into the Flash private var damage:Number;
Player. public function SpaceShip ( )
 The built-in Sound {
class to create speed = 100;
Sound objects, and damage = 0; }
use setVolume() & public function
loadSound() fireMissile
methods. ( ):Void
{ // Code that fires a missile goes
here. } public function thrust ( ):Void
{ // Code that propels the ship goes
here. }
11
}
Key Object-Oriented Prog. Concepts (Contd…)
Object Creation
 Objects are created (instantiated) with the new
operator, as in:
 new ClassName( )
where ClassName is the name of the class from
which the object will be created.
 Ex. new SpaceShip( )
 var ship:SpaceShip = new SpaceShip( );
 Each object is a discrete data value that can be
stored in a variable, an array element, or even a
property of another object.
12
Key Object-Oriented Prog. Concepts (Contd…)
Object Usage
 An object's methods provide its capabilities (i.e., behaviors)
—things like "fire missile," "move," and "scroll down."
 Methods and properties that are defined as public by an
object's class can be accessed from anywhere in a program.
 By contrast, methods and properties defined as private can
be used only within the source code of the class or its
subclasses.
 To invoke a method, we use the dot operator (i.e., a period)
and the function call operator (i.e., parentheses).
 For example: ship.fireMissile( );

 To set a property, we use the dot operator and an equals


sign. For example: ship.speed = 120;

 To retrieve a property's value, we use the dot operator on its


own. For example: trace(ship.speed); 13
Key Object-Oriented Prog. Concepts (Contd…)
Encapsulation

 Objects are said to encapsulate their property values


and method source code from the rest of the program.
 An object's private properties and the internal code
used in its methods (including public methods)
 It allows different programmers to work on different
classes independently
 A class can be tested thoroughly before being
deployed.
The same test code can be used to reverify the class's
operation even if the code within the class is refactored

14
Key Object-Oriented Prog. Concepts (Contd…)
Datatypes

 Each class in an object-oriented program can be thought


of as defining a unique kind of data, which is formally
represented as a datatype in the program.
 Date datatype supports various properties and
methods uniquely associated with dates
 Datatypes are used to impose limits on what can be
stored in a variable, used as a parameter, or passed as
a return value.
 Example: public var speed:Number

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

 Create one or more classes in .as files.


 Create a .fla file.
 On frame 1 of the .fla file, add code that creates
an object of a class.
 Optionally invoke a method on the object to
start the application.
 Export a .swf file from the .fla file.
 Load the .swf file into the Flash Player.

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

 To enable type checking for any of the preceding


items, we declare the item's type using post-colon
syntax
 Declaring an item's type tells the compiler what kind
of data it should contain.
29
Type Syntax (Contd…)
 The compiler can warn us of two possible error
conditions:
 If a value of an incompatible type is stored in a
variable, passed as a function parameter, or
returned by a function, the compiler generates a
type mismatch error.
 If a nonexistent property or method is accessed
through a typed variable, function parameter, or
function return value, the compiler generates an
error explaining that the property or method cannot
be found
30
Declaring Variable and Property Datatypes
 To declare the datatype of a variable or property, use the
following syntax:
var variableOrPropertyName:datatype;
Ex1.Create a variable that can contain only data compatible with
the Date datatype.
var currentTime:Date;
EX2. Store a Date instance in the currentTime variable.
currentTime = new Date( );

 We could also reduce the preceding two lines to a single step:


var currentTime:Date = new Date( );
31
Declaring Variable and Property Datatypes (Contd..)
 Once a variable's datatype is declared, it is fixed until the
variable is destroyed.
 Type checking is intended to help you write better code
more
quickly var currentTime:Date;
var currentTime:Number;
 In ActionScript 2.0, the preceding code does not change the
datatype of currentTime to Number.
 The second line is simply ignored and later attempts to assign a
numeric value to currentTime will generate errors.
 Instead of redeclaring a variable's datatype, you should use
two separate variables when you need to store values of two
different datatypes.
32
Declaring Method Parameter and Return Value
Datatypes
 Declaring the datatype of method or function parameters and
return values:
function methodName (param1Name:param1Type,
param2Name:param2Type):returnType {
// ...
}
 Functions that return no value should specify a returnType of
Void.
 Storing the return value of a function or method in a variable
or property of an incompatible type causes a type mismatch
error.
33
Post-Colon Syntax
Ex: function sum (x:Number, y:Number):Number {
return x+y;
}
var result:SClass = sum(10, 20);
 ActionScript 2.0 uses the following, slightly unusual syntax
for type declarations:
variableOrPropertyName:datatype = value;
 By contrast, Java and C++ use:
datatype variableName = 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

panel display 1 2 3 (line by line)


Defining Classes
 A class is a template for the creation of objects. Classes are
the building blocks of an object-oriented program.
 class declaration:
class ClassIdentifier { }
where ClassIdentifier is the name of the
class
E.x.: class Box {}
 A class definition must reside in an external plain text file that
has the extension .as.
 Everything between the curly braces in a class declaration
constitutes the class definition block, or more informally, the
class body.
45
The class body can contain:
 A constructor function (used to initialize instances
of the class)
 Variable definitions (the class's properties)
 Function definitions (the class's methods)
 #include directives, which can include files
containing properties, methods, and constructor
functions
 Metadata tags used in Flash MX 2004
components
 Comments
 Class definitions cannot be nested, and no other 46
code can appear in a class definition.
Example
class Box {
private static var inited:Boolean = false;
public function Box ( ) {
if (!inited) { init( ); } } private
static function init( ):Void {
if (100 == (10*10)) {
trace(" One hundred is ten times ten );
} inited = true; }}
"
 The term instance member refers to either an instance
property or an instance method, while the term class
member refers to either a class property or a class method
47
Constructor Functions (Take 1)
 When we create an object, we also want to
initialize it.
 Ex. Box Class: Initialize the new
instance's size (i.e., set its width and
height properties)
 Represent the new instance
on screen (i.e., call the draw(
) method)
 To initialize and perform setup tasks for new objects of
a class, we create a constructor function.
 The constructor function executes automatically
each time an instance is created. 48

 Typically, when we create a class, we immediately


Constructor Functions (Take 1) (Contd…)
 class Box {
public function Box ( ) {
}}
 Now that our Box class has an empty constructor
function, we'll give the class some properties and
methods.
 When no constructor is provided for a class,
ActionScript adds an empty one automatically at
compile time.

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

of the function call operator, ( ).


A class with getter and setter methods

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:

var viewer:ImageViewer = new ImageViewer(this, 1);


viewer.loadImage("picture.jpg");
Using ImageViewer in a Movie (Contd…)
 Let's export our imageViewer.swf file and test it in Flash's Test
Movie mode, as follows:
 Choose Control -> Test Movie. The .swf file should play,
and your image should load and appear.
 When you're finished marveling at your work, choose
File -
> Close to return to the imageViewer.fla file.
 To change imageViewer.fla's export settings to support
playback in Flash Player 6, follow these steps:
 Choose File -> Publish Settings.
 On the Flash tab of the Publish Settings dialog box, select
Flash Player 6 as the Version option.
 Click OK.
Preloading the ImageViewer Class
 Let's change our imageViewer.fla file so that the classes it
uses aren't loaded until frame 10:
 Choose File -> Publish Settings.
 In the Publish Settings dialog box, on the Flash tab, next to
the ActionScript Version, click Settings.
 In the ActionScript Settings dialog box, for Export Frame for
Classes, enter 10.
 Click OK to confirm the ActionScript Settings.
 Click OK to confirm the Publish Settings.
 Now let's add a very basic preloader to our imageViewer.fla
file so load progress is reported while the ImageViewer class
loads. When loading is complete, we'll advance the playhead
to frame 15 where we'll instantiate ImageViewer (as we
previously did on frame 1).
Preloading the ImageViewer Class (Contd..)
 First, we'll make the timeline 15 frames long, as follows:
 In the main timeline of imageViewer.fla, select frame 15 of the scripts
layer.
 Choose Insert -> Timeline ->Keyframe (F6).
 Next, we'll add a labels layer with two frame labels, loading and main. The
labels designate the application's loading state and startup point,
respectively.
 Choose Insert ->Timeline ->Layer.
 Double-click the new layer 's name and change it to labels.
 At frames 4 and 15 of the labels layer, add a new keyframe (using Insert -
>Timeline ->Keyframe).
 With frame 4 of the labels layer selected, in the Properties panel, under
Frame, change <Frame Label> to loading.
 With frame 15 of the labels layer selected, in the Properties panel, under
Frame, change <Frame Label> to main.
Now add the preloader script to the scripts layer:
 At frame 5 of the scripts layer, add a new keyframe (using
Insert ->timeline ->Keyframe).
 With frame 5 of the scripts layer selected, enter the following
code into the Actions panel:
if (_framesloaded == _totalframes) {
gotoAndStop("main");}
else {
gotoAndPlay("loading");
}
 Next, we'll move the code that creates our
ImageViewer
instance from frame 1 to frame 15 of the scripts layer:
 Select frame 1 of the scripts layer.
 In the Actions panel, cut (delete using Ctrl-X or Cmd-X) the
following code from frame:
var viewer:ImageViewer = new ImageViewer(this, 1);
viewer.loadImage("picture.jpg");
 With frame 15 of the scripts layer selected, paste (using Ctrl-
V ) the code you deleted in Step 2 into the Actions panel.
 Finally, we'll add a loading message that displays while the
ImageViewer class loads:
 With frame 1 of the scripts layer selected, enter the following
code into the Actions panel:
this.createTextField("loadmsg_txt", 0, 200, 200, 0, 0);
loadmsg_txt.autoSize = true;
loadmsg_txt.text = "Loading...Please wait.";
 With frame 15 of the scripts layer selected, enter the
following code at the end of the Actions panel
loadmsg_txt.removeTextField( );
ImageViewer Implementation (Take 2)
 The third and fourth requirements: cropping the image and
giving it a border. We must apply a mask to it, which hides
unwanted areas of the image from view.
 We'll add parameters to the ImageViewer constructor to
specify the size of the mask and the position of the cropped
image.
 To create border, we'll create a movie clip, then draw a square
outline in it.
Splitting out the work into separate methods
has the following benefits:
 It makes the code more intelligible.
 It simplifies the testing process (testing each
method individually is easier than testing a large
block of code that performs many operations).
 It allows assets to be created and re-created
independently (e.g., the border on an image can
change without reloading the image).
 It allows asset-creation operations to be modified
or overridden independently (e.g., a new border-
creation routine can be coded without disturbing
other code).
Table The ImageViewer class's new
instance methods that create movie clips
Method name Method descriptio
Invokes individual methods to create the container,
buildViewer( )
image, mask, and border clips

createMainContainer( ) Creates the container_mc clip


createImageClip( ) Creates the image_mc clip
createImageClipMask( ) Creates the mask_mc clip
createBorder( ) Creates the border_mc clip

•A reference to the target clip to which container_mc should be


attached
•A list of depths indicating the visual stacking order of the container,
image, mask, and border clips
•The style (line weight and color) of the border around the image
Table The ImageViewer class's instance
and class properties
Property name Type Property description
A reference to the main container clip, which contains all movie
container_mc Instance
clips used by each ImageViewer instance

A reference to the clip that will contain the container_mc


target_mc Instance
clip, as specified by the ImageViewer constructor

The depth on which container_mc is created in target_mc,


containerDepth Instance
as specified by the ImageViewer constructor

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:

You might also like