149
ActionScript 3.0 Fundamentals Saurabh Narula http://blog.saurabhnarula.com/

ActionScript 3.0 Fundamentals

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: ActionScript 3.0 Fundamentals

ActionScript 3.0 Fundamentals

Saurabh Narulahttp://blog.saurabhnarula.com/

Page 2: ActionScript 3.0 Fundamentals

Discussion Areas

• ActionScript 3.0 Introduction• AVM2• Programming Fundamentals• ActionScript Language and Syntax • Object Oriented Programming in

ActionScript

Page 3: ActionScript 3.0 Fundamentals

ActionScript is the programming language for Adobe Flash Platform.

Page 4: ActionScript 3.0 Fundamentals

Language specification is open source

Open Source Compiler – as part of Flex SDK

Open source Virtual Machine – Mozilla Tamarin

Page 5: ActionScript 3.0 Fundamentals

Whats not open source ..Flash Player

AIR

Page 6: ActionScript 3.0 Fundamentals

Initially designed for controlling simple 2D vector animations, few interactivity features (may be that’s why its single

threaded)

Page 7: ActionScript 3.0 Fundamentals

ActionScript executes in ActionScript Virtual Machine (AVM)

A new ActionScript Virtual Machine, called AVM2 – significant performance

improvements over older AVM

Page 8: ActionScript 3.0 Fundamentals

Before we get going on ActionScript fundamentals .. Lets have a brief look

and understand what is a virtual machine ..

Page 9: ActionScript 3.0 Fundamentals

Virtual Machine is essentially a virtual environment/OS running within

a actual/host operating systems.

Page 10: ActionScript 3.0 Fundamentals

In case of AVM, we talk about Process (Application) Virtual

Machines and not System (Platform) Virtual Machines.

Page 11: ActionScript 3.0 Fundamentals

Process VMs provide a platform-independent programming

environment that abstracts details of the underlying hardware or OS. Allows program to execute the same way on

all platforms.

Page 12: ActionScript 3.0 Fundamentals

Process VM provide high level abstraction, for a high level

programming language. This is done using an interpreter

Page 13: ActionScript 3.0 Fundamentals

Programmer writes code in high level/human readable form which a

machine can not understand .. so this source code has to be converted into

machine code, this conversion is performed by Interpreter.

Page 14: ActionScript 3.0 Fundamentals

Compiler makes the conversion once.Interpreter converts it every time a

program is executed.

Page 15: ActionScript 3.0 Fundamentals

Just in time Compilation (JIT) – offers improved runtime performance

than interpreter.

Page 16: ActionScript 3.0 Fundamentals

Interpreter interpret the byte code or sometimes interpret source code

directly without having a byte code. These techniques offer lower

performance.

Page 17: ActionScript 3.0 Fundamentals

In case of JIT, a compiler can be used during execution – dynamic

compilation. Remember – compilation from byte code to machine code is much faster than compiling from

source.

Page 18: ActionScript 3.0 Fundamentals

AVM2 takes ActionScript bytecode ABC file as an input.

Page 19: ActionScript 3.0 Fundamentals

AVM2 Architecture

Page 20: ActionScript 3.0 Fundamentals

GC in flash player does not work constantly, only triggered by

allocations.

Page 21: ActionScript 3.0 Fundamentals

GC in flash player is iterative, doesn’t guarantee to find all collectible blocks

in one pass.

Page 22: ActionScript 3.0 Fundamentals

GC works by

starting at the top of the object trees – Stage, ApplicationDomain/Class Definitions, Stack/Local Variables

Mark the object and any objects they reference.

Go through the heap and free anything that isn't marked.

Page 23: ActionScript 3.0 Fundamentals

ActionScript is based on ECMAScript

Page 24: ActionScript 3.0 Fundamentals

Event model based on the Document Object Model (DOM) Level 3 Events

Specification

Page 25: ActionScript 3.0 Fundamentals

DOM is a convention for representing and interacting with objects in HTML,

XML type documents.

Page 26: ActionScript 3.0 Fundamentals

Variables consists of 3 different parts – name, type of the data, actual value

in computer’s memory

Page 27: ActionScript 3.0 Fundamentals

Constant is same as variable but can be assigned only once.

Page 28: ActionScript 3.0 Fundamentals

Using constants than a literal value makes code more readable. Change the value at one place than having it changed everywhere if using a hard-

coded literal value. For example INTREST_RATE

Page 29: ActionScript 3.0 Fundamentals

Data types

Fundamental – single value like string, number, int, boolean etc ..

Complex – set of values like Date.

Page 30: ActionScript 3.0 Fundamentals

Creating objects is a way of organizing your code. In OOP related

information and functionality is grouped together in form of objects.

Page 31: ActionScript 3.0 Fundamentals

Class is a template or a blueprint of how object should look like, basis of

the object creation.

Page 32: ActionScript 3.0 Fundamentals

A Class can have Properties, Methods, Events.

Page 33: ActionScript 3.0 Fundamentals

Property is data/information bundled within the object.

Page 34: ActionScript 3.0 Fundamentals

To access a property you use “variable name-dot-property

name” structure.

Page 35: ActionScript 3.0 Fundamentals

A Method is an operation that object can perform, are not value

placeholders.

Page 36: ActionScript 3.0 Fundamentals

Event is essentially an event that happens which ActionScript is aware of

and can respond to.

Page 37: ActionScript 3.0 Fundamentals

Event Handling is an action that you perform in response to a particular

event.

Page 38: ActionScript 3.0 Fundamentals

Three important elements of Event handling – even source, event,

response.

Page 39: ActionScript 3.0 Fundamentals

function eventResponse(eventObject:EventType):void{

// Actions performed in response to the event go here.}

eventSource.addEventListener(EventType.EVENT_NAME, eventResponse);

Page 40: ActionScript 3.0 Fundamentals

Event handling -

Compiler makes note of all the eventResponse() functions.

Event source keeps a list of functions that are listening to each of its events.

When the event happens, object is created for that event’s class and passes it on to eventResponse function.

Page 41: ActionScript 3.0 Fundamentals

You directly instantiate a visual object by using it in MXML.

For non visual objects you can instantiate them by using new

operator or by assigning a literal value. Both approaches are same with

a difference of calling base class constructor when using the new

operator.

Page 42: ActionScript 3.0 Fundamentals

You can build Flash applications using ActionScript 3.0 without using

Flex SDK (create AS only project in Flash Builder), you can add AS code to

frames in a timeline in Flash Professional.

Page 43: ActionScript 3.0 Fundamentals

You can choose to Embed code in MXML files inside <fx:script> tag,

alternatively you can import ActionScript code from an external file and specify the source attribute of the <fx:script> tag. You can also import the unstructured code using the

include statement.

Page 44: ActionScript 3.0 Fundamentals

Include an ActionScript Class using import statement.

Page 45: ActionScript 3.0 Fundamentals

Flash Builder can be used to create apps using Flex SDK, and ActionScript

only projects.

Page 46: ActionScript 3.0 Fundamentals

You use Flash Professional when you want to create your visual assets

(graphics, interactivities etc) and work with timeline/frames and write code in

the same application.

Page 47: ActionScript 3.0 Fundamentals

Other third party tools – FDT, TextMate (with AS, Flex bundles) etc.

Page 48: ActionScript 3.0 Fundamentals

Class Design Considerations ..

A class can be type value object, display object, supporting class.

Page 49: ActionScript 3.0 Fundamentals

Class Design Considerations ..

Your class can dispatch events if other parts of application need to know of

some change.

Page 50: ActionScript 3.0 Fundamentals

Class Design Considerations ..

Consider creating a subclass if a class exists with a similar functionality.

Page 51: ActionScript 3.0 Fundamentals

Lets take a detailed look at ActionScript 3.0 language and

syntax.

Page 52: ActionScript 3.0 Fundamentals

Objects and Classes ..

All classes, built in or user defined derive from Object class.

Page 53: ActionScript 3.0 Fundamentals

Objects and Classes ..

var obj:*; //untyped object

key differentiator – can hold undefined value, variable of type object cannot

hold undefined.

Page 54: ActionScript 3.0 Fundamentals

Packages and namespaces ..

Related concepts but not same.

Page 55: ActionScript 3.0 Fundamentals

Packages ..

Implemented using namespaces (we will see later ..)

Page 56: ActionScript 3.0 Fundamentals

Packages ..

You can have variables, function, statements at the top level (and not

just classes) but can only be public or internal.

Page 57: ActionScript 3.0 Fundamentals

Packages ..

Doesn’t support private classes

Page 58: ActionScript 3.0 Fundamentals

Packages ..

Main benefit – helps in avoiding name conflicts

Page 59: ActionScript 3.0 Fundamentals

Packages ..

Import statements should be as specific as possible.

Import TestPackage.*; //avoid this – may lead to unexpected name conflicts.

Import TestPackage.SomeClass;

Page 60: ActionScript 3.0 Fundamentals

Packages ..

Default access specifier for all members of package is internal.

Page 61: ActionScript 3.0 Fundamentals

Packages ..

Resolving name conflicts –

import samples.SampleCode;import langref.samples.SampleCode;

var mySample:SampleCode = new SampleCode(); // name conflict

//use fully qualified names to resolve name conflictsvar sample1:samples.SampleCode = new

samples.SampleCode();var sample2:langref.samples.SampleCode = new

langref.samples.SampleCode();

Page 62: ActionScript 3.0 Fundamentals

Namespaces ..

Create your own namespace to define your own access control specifier.

Page 63: ActionScript 3.0 Fundamentals

Namespaces ..

You can attach a URI to the namespace definition, this makes sure

that the definition is unique. If URI is not defined, compiler creates a unique identifier string in place of

URI.

Page 64: ActionScript 3.0 Fundamentals

Namespaces ..

Cannot redefine a namespace in a same scope.

Page 65: ActionScript 3.0 Fundamentals

Namespaces ..

Can apply only one namespace to each declaration.

Page 66: ActionScript 3.0 Fundamentals

Namespaces ..

If you apply a namespace, you cannot also apply access control specifier.

Page 67: ActionScript 3.0 Fundamentals

Packages are abstractions built on top of namespaces.

Page 68: ActionScript 3.0 Fundamentals

mx_internal identifier used in Flex SDK

Page 69: ActionScript 3.0 Fundamentals

Variable Scope ..

There is no block level scope, interesting implication of this is that

you can read or write variable before it is declared.

Page 70: ActionScript 3.0 Fundamentals

Data Types ..

Primitive type (boolean, int, number, string, uint)

objects are stored as immutable objects, which means passing by

reference is same as passing by value.

Immutable objects - When you have a reference to an instance of object,

the content of the instance can not be altered.

Complex types/values are passed as reference.

Page 71: ActionScript 3.0 Fundamentals

Type Checking ..

Can occur at both compile and runtime.

Page 72: ActionScript 3.0 Fundamentals

Type Checking ..

You can set compiler to run in strict mode – type checking at both

compile time and runtime or

standard mode – only at runtime

Page 73: ActionScript 3.0 Fundamentals

Type Checking ..

Compile time checking is favored in case of large projects, catching type

errors as early as possible is important.

Page 74: ActionScript 3.0 Fundamentals

Type Checking ..

when you use untyped object, you are not eliminating type checking but

deferring it to the runtime.

Page 75: ActionScript 3.0 Fundamentals

Type Checking ..

Upcast – Use base class to declare the type of a class instance but use a

subclass to instantiate it.

Page 76: ActionScript 3.0 Fundamentals

is operator ..

1. Checks if the object is an instance of a particular class, 2. checks the inheritance hierarchy, 3. and if an object is an instance of a class that implements a particular interface.

Page 77: ActionScript 3.0 Fundamentals

as operator ..

Returns the value of the expression instead.

Helps in ensuring that you are using a correct type.

Page 78: ActionScript 3.0 Fundamentals

Dynamic classes ..

Can attach properties and methods outside the class definition.

Page 79: ActionScript 3.0 Fundamentals

Dynamic classes ..

Type checking on dynamic properties is done at the runtime.

Methods attached dynamically do not have access to private properties

References to public properties or methods should be qualified with this

or class name.

Page 80: ActionScript 3.0 Fundamentals

Data Types ..

Primitive – Boolean, int, Null, Number, String, Uint, void

Complex – Object, Array, Date, Error, Function,

Page 81: ActionScript 3.0 Fundamentals

Type Conversions ..

Type conversions can be either implicit (coercion) or explicit (casting). Implicit conversions usually happen at the run

time.

Page 82: ActionScript 3.0 Fundamentals

Implicit Conversions ..

Can happen at runtime – in assignment statements, when values passed as

function arguments, when values are returned from functions, when using +

operator

Page 83: ActionScript 3.0 Fundamentals

Implicit Conversions ..

For user-defined types, implicit conversions succeed when the value to

be converted is an instance of the destination class or a class that

derives from the destination class

Page 84: ActionScript 3.0 Fundamentals

Implicit Conversions ..

For primitive types, implicit conversion happens the same way as

in case of explicit conversion.

Page 85: ActionScript 3.0 Fundamentals

Explicit Conversions ..

Good for type safety, will save you from any type conversion errors that

might happen at the runtime.

Page 86: ActionScript 3.0 Fundamentals

Casting to int, uint, Number ..

Can cast any data type to one of these, if the conversion fails then

default value 0 for int & uint is assigned and Nan for Number.

Page 87: ActionScript 3.0 Fundamentals

Casting to Boolean ..

Casting to Boolean from numeric types results in false if the numeric value is 0

and true otherwise.

Page 88: ActionScript 3.0 Fundamentals

Casting to String ..

From any numeric types .. Returns a string representation of number, in case of arrays ..a comma delimited

string of all array elements would be returned.

Page 89: ActionScript 3.0 Fundamentals

ActionScript syntax ..

ActionScript is case sensitive.

Page 90: ActionScript 3.0 Fundamentals

ActionScript syntax ..

dot operator, literals, semicolons, parentheses, comments, keywords,

reserve words, constants.

Page 91: ActionScript 3.0 Fundamentals

Operators, Operator precedence and associatively ..

Page 92: ActionScript 3.0 Fundamentals

Primary Operators ..

Used for initializing array, object, group expression, calling a constructor

etc. For eample [], {x:y}, (), new resp.

Page 93: ActionScript 3.0 Fundamentals

Other Operators ..

Postfix, Unary, multiplicative, additive, bitwise shift, relational, equality,

bitwise logical, logical, conditional, assignment.

Page 94: ActionScript 3.0 Fundamentals

Conditional Statements ..

If, if .. else if, switch,

Page 95: ActionScript 3.0 Fundamentals

Looping ..

for, for .. In, for each .. In, while, do .. while

Page 96: ActionScript 3.0 Fundamentals

Functions ..

function statements vs. function expressions

Page 97: ActionScript 3.0 Fundamentals

Function statements ..

Less verbose, less confusing.

Page 98: ActionScript 3.0 Fundamentals

Function Expressions ..

Common use is that they are used only once and then discarded.

Page 99: ActionScript 3.0 Fundamentals

Difference between function expression & function statement ..

In case of dynamic classes/objects, delete has no effect on function

statements

Page 100: ActionScript 3.0 Fundamentals

Difference between function expression & function statement ..

Can call function statement even before they are defined, not in case of

fn expressions

Page 101: ActionScript 3.0 Fundamentals

Functions ..

return statement terminates the function, any statement after return is

not executed.

Page 102: ActionScript 3.0 Fundamentals

Nested functions ..

Only available within its parent function unless a reference to the function is passed to outside code

(function closures).

Page 103: ActionScript 3.0 Fundamentals

Function parameters ..

All arguments are passed by reference except primitive types.

Page 104: ActionScript 3.0 Fundamentals

Functions parameters ..

Number of arguments sent to a function can exceed the number of

parameters defined for that function.

Page 105: ActionScript 3.0 Fundamentals

Default parameters ..

Is similar to making a parameter as optional, a parameter with no default value becomes a required parameter.

All parameters with default values should ideally be placed in the end of parameter list in function signature.

Page 106: ActionScript 3.0 Fundamentals

The arguments object ..

Arguments is an array that includes all parameters passed to a function,

argument.callee provides a reference to a function itself, which is useful for

recursive calls (in function expressions).

Page 107: ActionScript 3.0 Fundamentals

.. (rest) parameter

specify array parameter that would allow you to accept any number of

comma delimited parameters. Use of this makes arguments array

unavailable.

Page 108: ActionScript 3.0 Fundamentals

.. (rest) parameter

can be used with other parameters, but should be the last parameter.

Page 109: ActionScript 3.0 Fundamentals

Function as Objects ..

Function passed as arguments to another function are passed as

reference.

Page 110: ActionScript 3.0 Fundamentals

Functions as objects ..

Functions can have properties, methods like an object. It even has a

read only property called length which stores the number of parameters

defined for that function.

Page 111: ActionScript 3.0 Fundamentals

Function scope ..

Same scope rules that apply to variables, apply to functions.

Page 112: ActionScript 3.0 Fundamentals

Scope Chain ..

At the time of execution a activation object gets created that stores parameters and local variables,

functions declared in the function body. We can not access activation

object.

Page 113: ActionScript 3.0 Fundamentals

Scope chain ..

Scope chain is created that contains the ordered list of objects, against which the identifier declarations

(variables) are checked.

Page 114: ActionScript 3.0 Fundamentals

Scope chain ..

Every function that executes has a scope chain, this is stored in an

internal property. For example, for a nested function the scope chain starts with its own activation object, followed

by its parent function’s activation object, until it reaches to global object. The global object is created when the ActionScript program begins, contains

all global variables and functions.

Page 115: ActionScript 3.0 Fundamentals

Function closures ..

Object that contains a snapshot of a function and its lexical environment.

Page 116: ActionScript 3.0 Fundamentals

Function closures ..

Function closures retain the scope in which they were defined.

Page 117: ActionScript 3.0 Fundamentals

Object Oriented Programming in ActionScript

Page 118: ActionScript 3.0 Fundamentals

Classes

abstract representation of object, usefulness of such an abstraction is

apparent in big projects.

Page 119: ActionScript 3.0 Fundamentals

Class attributes ..

Dynamic – allow properties (classes and properties) to be added at

runtime.Final – can not extend the class.Internal – visible only inside the

current package.Public – visible everywhere

Page 120: ActionScript 3.0 Fundamentals

Classes ..

Can have a static property and instance property with the same name

in the same class.

Page 121: ActionScript 3.0 Fundamentals

Classes ..

You can have statements in the class definition, which would execute only

once.

Page 122: ActionScript 3.0 Fundamentals

Class property attributes ..

Internal, private, protected, public, static, User defined namespaces.

Page 123: ActionScript 3.0 Fundamentals

Private variable ..

In case of dynamic classes, accessing a private variable returns undefined

instead of an error.

Page 124: ActionScript 3.0 Fundamentals

Private variables ..

Trying to access a private variable in strict mode using dot operator will generate a compile time error, and

undefined in case of accessing using [] bracket.

In standard mode, both cases will return undefined.

Page 125: ActionScript 3.0 Fundamentals

Static ..

Can be used with var, const, function. Attach property to class rather than to

instance of the class.

Page 126: ActionScript 3.0 Fundamentals

Static ..

Static properties are part of a subclass’s scope chain, within a

subclass a static variable or method can be used without referencing its

class name.

Page 127: ActionScript 3.0 Fundamentals

Variable ..

Can be declared using var and const keyword.

Page 128: ActionScript 3.0 Fundamentals

Variable ..

variable declared as both const and static must be initialized at the same

time as you declare it.

Page 129: ActionScript 3.0 Fundamentals

Instance variables ..

Cannot override var/const directly, can override setters/getters though.

Page 130: ActionScript 3.0 Fundamentals

Constructor methods ..

Can only be public, doesn’t return any value.

Page 131: ActionScript 3.0 Fundamentals

Constructor methods ..

Can explicitly call the super class constructor by using super(), compiler

calls it if not explicitly called.

Page 132: ActionScript 3.0 Fundamentals

Constructor methods ..

When using super statement with super(), always call super() first.

Page 133: ActionScript 3.0 Fundamentals

Static methods ..

Does not affect a specific instance of a class, you can use this or super

within the body of the static method. Not inherited but are in scope.

Page 134: ActionScript 3.0 Fundamentals

Instance methods ..

Redefine an inherited method, final attribute is used to prevent subclasses

from overriding a method.

Page 135: ActionScript 3.0 Fundamentals

Getters and setters ..

Access class properties which are private as if you are accessing directly

instead of calling a method. Avoids using names like getPropertyName(),

setPropertyName()

Page 136: ActionScript 3.0 Fundamentals

Getters and setters ..

Can use override attribute on getter and setter functions.

Page 137: ActionScript 3.0 Fundamentals

Bound methods ..

Similar to function closure, this reference in a bound method remains bound to the instance that implements the method, whereas this reference is

generic in case of function closure.

Page 138: ActionScript 3.0 Fundamentals

Enumerations ..

Custom data types that you create to encapsulate small set of values.

Page 139: ActionScript 3.0 Fundamentals

Embedded asset classes ..

[Embed] metadata tag, @Embed in MXML.

Page 140: ActionScript 3.0 Fundamentals

Interfaces ..

Method declarations that allow unrelated objects to communicate with

each other, i.e serves as a protocol.

Page 141: ActionScript 3.0 Fundamentals

Interfaces ..

Any class that implements interface is responsible for defining the method

implementations.

Page 142: ActionScript 3.0 Fundamentals

Interfaces ..

Can not include variables or constants but can include getters and setters.

Page 143: ActionScript 3.0 Fundamentals

Interfaces ..

Can be public or internal. Method definitions inside an interface can not have access specifiers. Interfaces can

extend another interface.

Page 144: ActionScript 3.0 Fundamentals

Interfaces ..

While implementing an interface, make sure number of parameters and

the data type of each parameter is same, in case of default parameter not necessary to specify the same default

values.

Page 145: ActionScript 3.0 Fundamentals

Inheritance ..

Code reuse. Subclass is guaranteed to possess all the properties of its base

class.

Page 146: ActionScript 3.0 Fundamentals

Inheritance ..

Can take advantage of polymorphism by inheriting and overriding methods.

Page 147: ActionScript 3.0 Fundamentals

Inheritance ..

Instance of a subclass can always be substituted for an instance of the base

class.

Page 148: ActionScript 3.0 Fundamentals

Inheritance - Overriding methods

Names of the parameters in the override method do not have to match

the names of the parameters in the base class, as long as the number of

parameters and the data type of each parameter matches.

Page 149: ActionScript 3.0 Fundamentals

Inheritance - Static Properties

If an instance property is defined that uses the same name as a static property in the same class or a

superclass, the instance property has higher precedence in the scope chain.