Intro.
静态类型语言(如 C++ 和 Java)在编译时执行类型检查。动态类型语言(如 Smalltalk 和 Python)在运行时执行类型检查。作为动态类型的语言,ActionScript 3.0在严格模式下,类型检查既发生在编译时也发生在运行时,但是在标准模式下,类型检查仅发生在运行时。(默认严格模式下运行)
on…Event is handler, e.g. onClipEvent
Function
² General
ActionScript 3.0 中的函数是对象。函数确实可以像其他任何对象那样具有属性和方法。每个函数都有一个名为 length 的只读属性,它用来存储为该函数定义的参数数量。(与 arguments.length 属性不同,后者报告发送给函数的参数数量。)
define 1 (函数语句):
function traceParameter(aParam:String) { trace(aParam); }
define 2 (函数表达式):
var traceParameter:Function = function (aParam:String) { trace(aParam); };
Note: 函数表达式主要用于动态行为(dynamic)的编程
可以嵌套函数
局部变量
e.g.
function localScope()
{ var strLocal:String = "local"; }
² 构造函数
构造函数只能是public方法
如果没有在类中定义构造函数方法,编译器会自动为您创建一个空构造函数。
² 参数
参数传递
在 ActionScript 3.0 中,所有的参数均按引用传递,因为所有的值都存储为对象。但是,属于基元数据类型(包括 Boolean、Number、int、uint 和 String)的对象具有一些特殊运算符,这使它们可以像按值传递一样工作,对函数体内的变量的任何更改都会导致在内存中生成这些值的新副本。
默认参数值
e.g. 下面的代码创建一个具有三个参数的函数,其中的两个参数具有默认值。当仅用一个参数调用该函数时,将使用这些参数的默认值。
function defaultValues(x:int, y:int = 3, z:int = 5):void { trace(x, y, z); }
defaultValues(1); // 1 3 5
² arguments 对象
+ arguments 对象是一个数组,其中包括传递给函数的所有参数。
+ arguments.length 属性报告传递给函数的参数数量。
+ arguments.callee 属性提供对函数本身的引用,这对于递归调用函数表达式很有用。
+ 在标准模式下, 实际调用参数的数量可以大于在函数中定义的参数数量(在严格模式下会编译器错误)
e.g.
for (var i:uint = 0; i < arguments.length; i++) { trace(arguments[i]); …
var factorial:Function = function (x:uint) { if(x == 0) { return 1; } else { return (x * arguments.callee(x - 1)); } } trace(factorial(5)); // 120 |
² ... (rest) 参数
接受任意多个以逗号分隔的参数.
... (rest) 参数还可与其他参数一起使用,前提是 ... (rest) 参数是列出的最后一个参数。
e.g.
function traceArgArray(x: int, ... args):void {
for (var i:uint = 0; i < args.length; i++) {
trace(args[i]);
traceArgArray(1, 2, 3); // 2 3
² Global Function
isNaN(), parseInt()
² function closure (函数闭包)
A function closure is an object that contains a snapshot of a function and its lexical environment. Function closures are created any time a function is executed apart from an object or a class.
如果您将函数定义为类定义的一部分或者将它附加到对象的实例,则该函数称为方法。如果您以其他任何方式定义函数,则该函数称为函数闭包。无论何时在对象或类之外的位置执行函数,都会创建函数闭包。
e.g.
function foo():Function { var x:int = 40; function rectArea(y:int):int // function closure defined { return x * y } return rectArea; } function bar():void { var x:int = 2; var y:int = 4; var myProduct:Function = foo(); trace(myProduct(4)); // function closure called } bar(); // 160 |
this 引用是通用的,这意味着调用函数时,该引用指向与函数关联的任何对象。
函数闭包与绑定方法之间的主要区别在于,绑定方法中 this 关键字的值始终引用它最初附加到的实例,而函数闭包中 this 关键字的值可以改变。
Detail: http://help.adobe.com/zh_CN/as3/learn/WSf00ab63af761f1702761490412937d6fc9b-7fc2.html
² Bound methods绑定方法 (method closure 闭包方法)
作为参数传递给函数的方法或作为值从函数返回的方法都是绑定方法。将方法当作参数传递时会自动创建绑定方法。
绑定方法中的 this 引用总是指向实现方法的原始对象。
e.g.
class ThisTest { private var num:Number = 3; function foo():void // bound method defined { trace("foo's this: " + this); trace("num: " + num); } function bar():Function { return foo; // bound method returned } } var myTest:ThisTest = new ThisTest(); var myFunc:Function = myTest.bar(); trace(this); // output: [object global] myFunc(); /* output: foo's this: [object ThisTest] output: num: 3 */ |
Detail: http://help.adobe.com/zh_CN/as3/learn/WSf00ab63af761f170-4ed0731912937da73f7-7ffe.html
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f30.html
Event
² General
event – eventObject.EventType
eventTarget.addEventListener(eventObject.EventType, eventListener);
Dispatch: To notify event listeners that an event has occurred.
Event object: 事件对象, An object that contains information about a particular event’s occurrence, which is sent to all listeners when an event is dispatched.
Event target: The object that actually dispatches an event.
event type: Every event object has an associated event type. Event types are stored in the Event.type property.
bubble: the event object is passed from the target node back through its ancestors until it reaches the Stage.
event flow: (as below)
² event sample
IEventDispatcher, addEventListener, TimeEvent, Event,
Event.ENTER_FRAME
function eventResponse(eventObject:EventType):void { // Actions performed in response to the event go here. }
eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse); myDisplayObject.addEventListener(MouseEvent.CLICK, clickHandler); // event or event objects: MouseEvent // event type: .CLICK, event target: myDisplayObject function startDragging(event:MouseEvent):void { draggedObject = DisplayObject(event.target); stage.addChild(draggedObject); square.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); // listener: startDragging |
package flash.events { public final class EventPhase { public static const CAPTURING_PHASE:uint = 1; public static const AT_TARGET:uint = 2; public static const BUBBLING_PHASE:uint= 3;
if (event.eventPhase == EventPhase.AT_TARGET) { myFunc(); |
标签
² [Embed]
e.g.
package { import flash.display.Sprite; import flash.media.SoundChannel; import mx.core.SoundAsset;
public class SoundAssetExample extends Sprite { [Embed(source="sound1.mp3")] public var soundCls:Class;
public function SoundAssetExample() { var mySound:SoundAsset = new soundCls() as SoundAsset; var sndChannel:SoundChannel = mySound.play(); } } } // 使用名为 soundCls 的变量来存储对该声音的关联嵌入资源类的引用 |
在 Flex 中,通过在 MXML 标签定义中使用 @Embed() 指令也可以嵌入资源。
Detail: http://help.adobe.com/zh_CN/as3/learn/WSf00ab63af761f170-4ed0731912937da73f7-7ffe.html
garbage collection
1. remove all references
myObject = null; delete myMap[myObject]; |
2. using weak references
An object that has weak references is eligible for garbage collection.
import flash.utils.Dictionary;
var myObject:Object = new Object(); var myMap:Dictionary = new Dictionary(true); myMap[myObject] = "foo"; myObject = null; // Make object eligible for garbage collection. Do not need to delete key myObject from myMap. |
Handling errors
error sample
Error, ArgumentError, IOError, ApplicationError, SecurityError, IllegalOperationError,
try { fileRef.upload("http://www.yourdomain.com/fileupload.cfm"); } catch (error:IllegalOperationError) { trace(error); // Error #2037: Functions called in incorrect sequence, or earlier // call was unsuccessful. } finally { … } // a run-time error is thrown synchronously because Flash Player determined that the browse() method was not called before the file upload was attempted |
Detail: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7eb3.html
Custom Error
public class AppError extends Error { public function AppError(message:String, errorID:int) { super(message, errorID);
try { throw new AppError("Encountered Custom AppError", 29); } catch (error:AppError) { trace(error.errorID + ": " + error.message); |
Display
Display List hierarchy
Adding display objects to the display list
var myText:TextField = new TextField(); myText.text = "Buenos dias."; this.addChild(myText); // or addChildAt() this.root.addChild(myTextField); // this.root points to the MovieClip display object container that contains the code |
DisplayObjectContainer
contains(): Determines whether a display object is a child of a DisplayObjectContainer.
getChildByName(): Retrieves a display object by name.
getChildIndex(): Returns the index position of a display object.
setChildIndex(): Changes the position of a child display object.
swapChildren(): Swaps the front-to-back order of two display objects.
swapChildrenAt(): Swaps the front-to-back order of two display objects, specified by their index values.
Loading display objects
var pictLdr:Loader = new Loader(); var pictURL:String = "banana.jpg" var pictURLReq:URLRequest = new URLRequest(pictURL); pictLdr.load(pictURLReq); this.addChild(pictLdr);
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/externalSwf.swf"); |
Detail: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e1f.html
Detail: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e36.html
Animation
movieClips
method sample
play(), stop(), gotoAndPlay(), gotoAndStop(), currentFrame, nextFrame(), prevFrame(),
Detail: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS87A7F983-30F3-40c7-A309-6A25462A7A57.html
Useful API
flash.display.DisplayObject
flash.display.Sprite à DisplayObjectContainer à InteractiveObject à DisplayObject à EventDispatcher à Object
flash.display.Stage / StageAlign / StageScaleMode
stage.displayState = StageDisplayState.FULL_SCREEN;
flash.display.MovieClip
flash.display.Loader
flash.events.MouseEvent
flash.net.URLRequest
flash.desktop.Clipboard
flash.desktop.ClipboardFormats
Algorithm
// Generate random values for the red, green, and blue color var red:Number = (Math.random() * 512) - 255; // similar for green, blue
|