CÁCH VIẾT CLASS TRONG FLASH

Thứ Tư, 15 tháng 9, 2010
  1. Class không soạn trong Actions panel mà viết trong 1 file riêng .as có tên file trùng với tên class (class UserClass {...} trong file UserClass.as)
  2. Cấu trúc chung 1 file class là:
    Trong file myHello.as Trong file fla
    Tên lớp (trùng với tên file)
    Khai báo biến (lần lượt public, private)
    Hàm conctructor (có tên trùng với tên lớp) là hàm đặc biệt khởi động các thành viên dữ liệu của 1 instance của lớp
    Các phương thức (methods)


    class myHello {
    private var myText:String = "Hello world";
    function myHello(){
    init();
    }
    private function init(){
    trace(myText);
    }
    }
    import myHello;
    var greet:myHello = new myHello();

    Kết quả biên dịch (trong output panel)



    Hello world

    Biến và hàm có thể là private hay public: private chỉ cho phép các hàm thành viên trong lớp truy cập còn public thì sử dụng chung cho các hàm khác lớp...

Person

Person.as
class Person
{
var age:Number;
var name:String;

function Person (myName:String, myAge:Number)
{
name = myName;
age = myAge;
}

function showInfo():String
{
return("Hello, my name is " + name + " and I'm " + age + " years old.");
}
}
createPerson.fla
var person_1:Person = new Person("Nate", 32);
var person_2:Person = new Person("Jane", 28);
trace(person_1.showInfo());
trace(person_2.showInfo());
Output
Hello, my name is Nate and I'm 32 years old.
Hello, my name is Jane and I'm 28 years old.

- Hàm constructor ở ví dụ dưới có 2 tham số (parameters) là myName và myAge được copy vào 2 biến instance là name và age
Class và instances
Trong lập trình Hướng Đối tượng (object-oriented program) thì class định nghĩa 1 kiểu object. Class mô tả properties (data) và behavior (methods) cho 1 object, khá giống với 1 sơ đồ nhà với các đặc tính xây dựng. Để sử dụng các properties và methods của 1 class nào đó, việc đầu tiên là tạo ra 1 instance you generally first create an instance of that class (except for classes that have static members). The relationship between an instance and its class is similar to the relationship between a house and its architectural blueprints.
Sử dụng file class (*.as): Dùng toán tử import như ví dụ file draw.as import draw;. Nếu file draw.as nằm ở trong thư mục con tên art thì import art.draw;
Đối với trường hợp built-in class thì k cần bước này
Tạo 1 đối tượng mới: Tạo 1 instance của 1 class cần toán tử new để gọi hàm constructor của class đó (hàm constructor có cùng tên với tên class). Instance tạo thành sẽ được gán cho 1 biến. Ví dụ như var song:Sound= new Sound(); //Tạo 1 instance của class Sound cho biến song
Đối với 1 vài trường hợp built-in class có class members (static members) k cần bước này Some built-in ActionScript classes have class members (or static members). Ví dụ như các properties của Math class đều là static nên muốn xác định số lớn nhất trong 2 số var largerNumber:Number = Math.max(10, 20);
Sử dụng properties và methods của object: Dùng toán tử dấu chấm (.) . Ví dụ sau dùng property length của Array class và method setVolume của Sound class
var my_array:Array = new Array("apples", "oranges", "bananas");
trace(my_array.length); // length is 3
var mySound:Sound = new Sound(this);
mySound.setVolume(50);
About class (static) members
Some built-in ActionScript classes have class members (or static members). Class members (properties and methods) are accessed or invoked on the class name, not on an instance of the class. Therefore, you don’t create an instance of the class to use those properties and methods.
For example, all the properties of the Math class are static. The following code invokes the max() method of the Math class to determine the larger of two numbers:
var largerNumber:Number = Math.max(10, 20);

All built-in Classes

http://flash-reference.icod.de/class-summary.html
Đối với các lớp lập sẵn trong Flash không cần dùng toán tử import khi tạo instance
Documentation for ActionScript classes includes syntax, usage information, and code samples for methods, properties, and event handlers and listeners that belong to a specific class in ActionScript (as opposed to global functions or properties). The classes are listed alphabetically and include new classes in Flash Player 8 that are found in the flash.* packages. If you are not sure to which class a certain method or property belongs, you can look it up in the Index.
Name Package Description
Accessibility Top Level The Accessibility class manages communication with screen readers.
arguments Top Level An arguments object is used to store and access a function's arguments.
Array Top Level The Array class lets you access and manipulate indexed arrays.
AsBroadcaster Top Level Provides event notification and listener management capabilities that you can add to user-defined objects.
BevelFilter flash.filters The BevelFilter class lets you add a bevel effect to a variety of objects in Flash.
BitmapData flash.display The BitmapData class lets you create arbitrarily sized transparent or opaque bitmap images and manipulate them in various ways at runtime.
BitmapFilter flash.filters The BitmapFilter base class for all image filter effects.
BlurFilter flash.filters The BlurFilter class lets you apply a blur visual effect to a variety of objects in Flash.
Boolean Top Level The Boolean class is a wrapper object with the same functionality as the standard JavaScript Boolean object.
Button Top Level All button symbols in a SWF file are instances of the Button object.
Camera Top Level The Camera class is primarily for use with Macromedia Flash Communication Server, but can be used in a limited way without the server.
capabilities System The Capabilities class determines the abilities of the system and player hosting a SWF file, which lets you tailor content for different formats.
Color Top Level Deprecated since Flash Player 8 — The Color class has been deprecated in favor of the flash.geom.ColorTransform class.
ColorMatrixFilter flash.filters The ColorMatrixFilter class lets you apply a 4 x 5 matrix transformation on the RGBA color and alpha values of every pixel on the input image to produce a result with a new set of RGBA color and alpha values.
ColorTransform flash.geom The ColorTransform class lets you mathematically adjust all of the color values in a movie clip.
ContextMenu Top Level The ContextMenu class provides runtime control over the items in the Flash Player context menu, which appears when a user right-clicks (Windows) or Control-clicks (Macintosh) on Flash Player.
ContextMenuItem Top Level The ContextMenuItem class allows you to create custom menu items to display in the Flash Player context menu.
ConvolutionFilter flash.filters The ConvolutionFilter class applies a matrix convolution filter effect.
CustomActions Top Level The methods of the CustomActions class allow a SWF file playing in the Flash authoring tool to manage any custom actions that are registered with the authoring tool.
Date Top Level The Date class lets you retrieve date and time values relative to universal time (Greenwich mean time, now called universal time or UTC) or relative to the operating system on which Flash Player is running.
DisplacementMapFilter flash.filters The DisplacementMapFilter class uses the pixel values from the specified BitmapData object (called the displacement map image) to perform a displacement of an object on the Stage, such as a MovieClip instance.
DropShadowFilter flash.filters The DropShadowFilter class lets you add a drop shadow to a variety of objects in Flash.
Error Top Level Contains information about an error that occurred in a script.
ExternalInterface flash.external The ExternalInterface class is the External API, an application programming interface that enables straightforward communication between ActionScript and the Flash Player container; for example, an HTML page with JavaScript, or a desktop application with Flash Player embedded.
FileReference flash.net The FileReference class provides a means to upload and download files between a user's computer and a server.
FileReferenceList flash.net The FileReferenceList class provides a means to let users select one or more files for uploading.
Function Top Level Both user-defined and built-in functions in ActionScript are represented by Function objects, which are instances of the Function class.
GlowFilter flash.filters The GlowFilter class lets you apply a glow effect to various objects in Flash.
GradientBevelFilter flash.filters The GradientBevelFilter class lets you apply a gradient bevel effect to various objects in Flash.
GradientGlowFilter flash.filters The GradientGlowFilter class lets you apply a gradient glow effect to a variety of objects in Flash.
IME System The IME class lets you directly manipulate the operating system's input method editor (IME) in the Flash Player application that is running on a client computer.
Key Top Level The Key class is a top-level class whose methods and properties you can use without a constructor.
LoadVars Top Level You can use the LoadVars class to obtain verification of successful data loading and to monitor download progress.
LocalConnection Top Level The LocalConnection class lets you develop SWF files that can send instructions to each other without the use of fscommand() or JavaScript.
Locale mx.lang The mx.lang.Locale class allows you to control how multilanguage text is displayed in a SWF file.
Math Top Level The Math class is a top-level class whose methods and properties you can use without using a constructor.
Matrix flash.geom The flash.geom.Matrix class represents a transformation matrix that determines how to map points from one coordinate space to another.
Microphone Top Level The Microphone class lets you capture audio from a microphone attached to the computer that is running Flash Player.
Mouse Top Level The Mouse class is a top-level class whose properties and methods you can access without using a constructor.
MovieClip Top Level The methods for the MovieClip class provide the same functionality as actions that target movie clips.
MovieClipLoader Top Level This class lets you implement listener callbacks that provide status information while SWF, JPEG, GIF, and PNG files are being loaded into movie clips.
NetConnection Top Level The NetConnection class provides the means to play back streaming FLV files from a local drive or HTTP address.
NetStream Top Level The NetStream class provides methods and properties for playing Flash Video (FLV) files from the local file system or an HTTP address.
Number Top Level The Number class is a simple wrapper object for the Number data type.
Object Top Level The Object class is at the root of the ActionScript class hierarchy.
Point flash.geom The Point class represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
PrintJob Top Level The PrintJob class lets you create content and print it to one or more pages.
Rectangle flash.geom The Rectangle class is used to create and modify Rectangle objects.
security System The System.security class contains methods that specify how SWF files in different domains can communicate with each other.
Selection Top Level The Selection class lets you set and control the text field in which the insertion point is located (that is, the field that has focus).
SharedObject Top Level The SharedObject class is used to read and store limited amounts of data on a user's computer.
Sound Top Level The Sound class lets you control sound in a movie.
Stage Top Level The Stage class is a top-level class whose methods, properties, and handlers you can access without using a constructor.
String Top Level The String class is a wrapper for the string primitive data type, and provides methods and properties that let you manipulate primitive string value types.
StyleSheet TextField The StyleSheet class lets you create a StyleSheet object that contains text formatting rules for font size, color, and other styles.
System Top Level The System class contains properties related to certain operations that take place on the user's computer, such as operations with shared objects, local settings for cameras and microphones, and use of the Clipboard.
TextField Top Level The TextField class is used to create areas for text display and input.
TextFormat Top Level The TextFormat class represents character formatting information.
TextRenderer flash.text The TextRenderer class provides functionality for the advanced anti-aliasing capability of embedded fonts.
TextSnapshot Top Level TextSnapshot objects let you work with static text in a movie clip.
Transform flash.geom The Transform class collects data about color transformations and coordinate manipulations that are applied to a MovieClip object.
Video Top Level The Video class enables you to display live streaming video on the Stage without embedding it in your SWF file.
XML Top Level Use the methods and properties of the XML class to load, parse, send, build, and manipulate XML document trees.
XMLNode Top Level An XML document is represented in Flash by the XML class.
XMLSocket Top Level The XMLSocket class implements client sockets that let the computer running Flash Player communicate with a server computer identified by an IP address or domain name.
XMLUI Top Level The XMLUI object enables communication with SWF files that are used as custom user interfaces for the flash authoring tool's extensibility features (such as Behaviors, Commands, Effects, and Tools).
Xem thêm bài viết cùng chuyên mục: ,

Ý kiến bạn đọc [ 0 ]


Ý kiến của bạn