Flash ActionScript 2.0 Basic Tutorial

Source: Internet
Author: User
Tags closing tag constructor continue count implement inheritance new features static class
Basic Tutorials

This translator: Egoldy
Article Source: http://www.ultrashock.com
Article Nature: Translation

ActionScript 2.0-Introduction

With the introduction of FLASHMX2004, Macromedia introduced a new type of script called AS2, and in the course of the tutorial we will learn about the new features of AS2. New object-oriented models and how to make AS1 scripts over to AS2.

Why we need a new scripting language.

If you just do some simple animations that don't need a new scripting language, there are many projects that don't require scripting language. If you really don't need to use scripting language then this tutorial will be a very short tutorial and now you can end it. :)

If you are a developer and are developing some more complex projects, then AS1 is a bit too weak or incompetent. AS1 is very strange for programmers who use mainstream languages such as java,c++,c# development programs. They are going to take some detours to learn AS1 especially in object-oriented programming.

In AS2, these programmers will find a lot of familiar syntax, AS2 like java. Jscript. NET and JavaScript 2.0 programmers will feel better, because AS2 's language base comes from ECMAScript EDITION 4.as2 can enable programmers to write more healthy programs, or to attract more programmers to learn about Flash.

Well, you probably don't develop programs, so do you like to develop games? Or to develop an interactive presentation. The good news is that AS2 has provided strong support for our development.

If you are not interested in learning AS2, don't worry. Because Macromedia retains the AS1 syntax. You just can't master the new features of the language. In fact, both AS2 and AS1 will be compiled into the same Bytescode during the final compilation. The reason for doing so is mostly to be compatible with FLASH6. OK. Below we will continue to study.

a little object-oriented programming in ActionScript 2.0-as1.0

Before we move to AS2, let me take a look at object-oriented programming at AS1. This section is important for people who are less aware of object-oriented programming in FLASH5 and FLASHMX. If you already know these, you can skip this section directly.

Although AS1 is not really an object-oriented programming language, developers have used it for object-oriented programming at some point. Everything in AS1 relies on the link between the prototype chain and the object. So using object-oriented in AS1 requires an understanding of the prototype chain (or the keyword of the prototype).

A AS1 class is like a function of a rule. method is attached to the prototype of this class. For example:

Wizard class
function Wizard () {
}
The Help () method is attached to the prototype of the wizard function.
Wizard.prototype.help = function () {
};

If we put help () directly in the wizard class classes. Flash does not find it when looking for properties and methods, because Flash is searching along the prototype chain. Instead, create an instance copy for all the Wizard classes. The following is the copy. function Wizard () {this.help=function () {}} that is created for each instance. For java,c# programmers. It would seem familiar to put the method code in the class, but for the sake of reusability of the code we should attach the method to the prototype chain of the class. In the following example, if we have two methods for a class, one is attached to the prototype chain and the other is placed directly in the class, Flash will first get the internal method.

As1_oop_01.fla
function TestClass () {
This.method = function () {
Trace ("Internal method");
}; This.prop = ">>> Internal prop";
}//Attach A to the prototype object of the class
TestClass.prototype.method = function () {
Trace ("Prototype method");
}; TestClass.prototype.prop = ">>> prototype prop";//Create An instance of the TestClass class
var w = new TestClass ();//Internal method are located before the prototype method
W.method ()//Replace The Internal method
W.method = function () {
Trace ("New method");
};
W.method ()//Delete The Internal method
Delete w.method;//The remaining is the prototype method
W.method ()//Test the properties
Trace (w.prop); w.prop = ">>> New prop";
Trace (w.prop);d elete W.prop;
Trace (W.prop);

The above example outputs the following:

From the above example, we can see that it is very confusing for beginners to use AS1 orientation. It's important to know where to write your code, because it may often come up with unexpected results, just as there is a popular word in business: But wait, there's more ....

new features in ActionScript 2.0-as2.0

New features in the AS2

AS2 is not really a new language, it is an upgrade based on AS1, if you basically mastered AS1 programming, then it should be easy to learn it. Let's take a look at the new things AS2 offers.

. Strict data types and compilation hints.

. Code hints based on data types.

. New keywords and attributes for OOP.

Class, Interface, extends, implements, public, private, static, dynamic, intrinsic, import, class path, GET, set

Let me take a look at the new features of each of these items below.

Strict data Types

In a more professional programming language, expression is dependent on the data type. The big advantage it gives us is that it helps the compiler to discover potential problems and get the wrong type of error message. It makes your code clear and readable.

The process of declaring a variable such as count in AS1 is as follows:

var count;

The procedure declared in AS2 should be this way.

var Count:number;

Note that its syntactic structure is:< variable >:< data type, which may seem strange to many java,c#,c++ programmers, which is actually the ECMA-262 Association's rules, which Macromedia Company is doing.

AS2 variables, functions, and return values support strict data types, as the following example function receives a string parameter to return a Boolean value.

function func (arg:string): boolean{};

When a function does not receive a parameter and returns any value, void is made as the data type.

function func (arg:void): void{};

This type of argument may seem strange in its form, but it is used in a large number of applications to write a component, meaning that there are currently no specified parameters. However, if you try to pass the parameters to this function, the compiler will not have any errors at compile time and also pass the parameters.

Although AS2 supports strict data types and is not actually executing this syntax, it is a good starting habit to use strict data to program when the compiler discovers that there is a data type that does not match the error message. It's good for us to have said it above. If you are using a strict data type to program, you should specify the use of AS2 at the time of publication, and specify the release as Flash PLAYER 7.

With strict data types, the new compiler provides you with a number of new compiler tips to prevent your movie from having type-worthy errors, but it may take a long time to debug during compilation.

Code Hints

The code hint in FALSHMX is based on the extension of the variable name, such as the _PB,_CB in MYPUSHBUTTON_PB,MYCOMBOBOX_CB, and in 2004 you will find that most of the variable extensions are not in effect, The new version of AS2 shows code hints with different conventions.

When a variable type is specified (if the variable type is valid for this class) the code hint for the method and property appears after the point, otherwise no code hint appears. Displays ComboBox code hints by specifying the data type:

var Combo:mx.controls.comboBox;
Combo.

You can view the default extension code prompts by opening the following file:

<flash installation Folder>\<language>\first Run\actionspanel\ascodehints.xml

Tip: Add a FLASHMX code hint to 2004

If you use 2004来 to edit your FLASHMX document, you can add part of the FLASHMX code hint to the 2004 code hint.

Copy <flash MX installation Folder>\<language>\first Run\actionspanel\customactions\uicomponents.xml, in the

<codehints>
<typeinfo pattern= "*_ch" object= "Fcheckbox"/>
<typeinfo pattern= "*_PB" object= "Fpushbutton"/>
<typeinfo pattern= "*_RB" object= "Fradiobutton"/>
<typeinfo pattern= "*_lb" object= "Flistbox"/>
<typeinfo pattern= "*_SB" object= "Fscrollbar"/>
<typeinfo pattern= "*_CB" object= "Fcombobox"/>
<typeinfo pattern= "*_sp" object= "Fscrollpane"/>
<typeinfo pattern= "Globalstyleformat" object= "Fstyleformat"/>
</codehints>

This section is copied to the <codehints></codehints> of the Ascodehints.xml file of the Flash MX uicomponents.xml file before the closing tag of the document. Notice the extra <codehints> mark to remove.

Now you can use the FLASHMX component code hints in 2004.

ActionScript 2.0-keywords and attributes for OOP

Here we will really look at the characteristics of AS2, in the early days it was often discussed that AS1 complex object-oriented programming was more than actual work, and now you'll soon see that you don't have to spend a lot of time arguing about how best to inherit, where to place your code and how to organize your code base.

Let's take a look at the OOP basics, the most basic unit of OOP is the object, which contains two parts: Code and data. Because an object is a self-contained form, its data and code (methods) do not need to be exposed. Like a black box, the object is responsible for managing its own data in its own way, through the communication of information between objects and objects. This information is delivered and received in a public or public manner. and the internal data and methods are not directly involved in it, this is the basic principle of OOP.

In OOP design, comparison is a big picture, to think about the focus and the goal to achieve, as well as the relationship between the various parts. By dividing this large image into smaller units and ensuring their own independence, the entire project is easy to complete. And these small units are called classes in OOP. All of these AS2 provide good support.

The following keywords are related to OOP:

Class interface extends implements
Public private static dynamic
Import Get Set intrinsic

We do not describe each keyword in the Mcromedia help document, which we can illustrate with an example. Note that keyword intrinsic is a keyword used internally by Mcromedia. There's no package in it, but it's the key to the package, but it's important to work with the classpath, like a package in other languages, like Java.

Now let's take a look at the example, the class in AS1, and rewrite it as a AS2 class.

Constructors
_global. Parent = function (name) {
This.init.apply (this, arguments);
};
Properties of the class
Parent.lastnames = new Array ();
Parent.prototype.init = function (name) {
This.lname = name;
Parent.lastNames.push (name);
This.id = parent.lastnames.length-1;
Trace ("Added '" + parent.lastnames[this.id] + "' at:" + this.id);
};
Parent.prototype.getLastName = function () {
return (This.lname);
};
Parent.prototype.setLastName = function (s) {
This.lname = s;
Parent.lastnames[this.id] = s;
};
Parent.prototype.getNames = function () {
return (Parent.lastnames);
};
Parent.prototype.addProperty ("LastName", Parent.prototype.getLastName, Parent.prototype.setLastName);
Parent.prototype.addProperty ("Names", Parent.prototype.getNames, NULL);

The code above is rewritten as AS2 to the following:

New keywords are applied in the following example: class, Private, public, static, get, set

Class Parent {
private var lname:string = "";
private Var Id:number;
private static var Lastnames:array = new Array ();
Constructors
Public Function Parent (name:string) {
Init.apply (this, arguments);
}
Private function init (name:string): Void {
LName = name;
Lastnames.push (name);
id = lastnames.length-1;
Trace ("Added '" + lastnames[id] + "' at:" + ID);
}
Public function Get LastName (): String {
return lName;
}
Public function set LastName (s:string): Void {
LName = s;
Lastnames[id] = s;
}
Public function Get Names (): Array {
return lastnames;
}
}

Execute the same class through the AS1 and AS2 above. We can see that the two are very similar, with the main differences taking AS2 as an example:

1. In the form of an external file such as. As, note that the name of the class is the same as the external file name.
2. AS2 is case-sensitive, and object and object are different in AS2.
3. The method of the class is defined inside the class.
4. The interior of a class is not allowed to appear in the inner class.
5. Keywords such as public,private,static are written in front of a class method or property.
6. The data type is written after the method or property name, as follows: name:string;
7. It is easier to create the Get|set method by using the following methods: [modifier] function get|set functionname (argument[:type,...]) [: Type] {}

the scope of ActionScript 2.0--this

Keyword This is a keyword that you can use arbitrarily, and you may also be aware of its use, but when a local variable and a class attribute share a name. If you want to specify the properties of a class, you must use this. The following example illustrates this problem.

1. Create a new Flash document and select ActionScript file as follows:

2. Place your file in a working directory called scopetest.as. Just like we mentioned before, keep your class name consistent with your file name.

3. Enter the following code:

Class Scopetest {
private var myvar:string = "I am the Class property!";
Public function dotest (void): void {
var myvar:string = "I am the local variable!";
Trace ("MyVar =" + MyVar);
Trace ("This.myvar =" + This.myvar);
}
}

4. Save your files.
5. Create a new flash document, save it as a Scopetest.fla file, and make sure that your class files are in the same directory.
6. Enter the following code on the first frame:

var mytest:scopetest = new Scopetest ();
Mytest.dotest ();

7. Test your Videos

ActionScript 2.0--Private or protected

One thing to be aware of in AS2 is the private property. Like Java, private members mean that only the class itself can be accessed. Subclasses cannot be accessed, including in the same classpath or package. Private properties, like other languages, are mostly for protection purposes.

Since this feature only takes effect at compile time, it is important that you ensure that the compiler obtains the proprietary methods and properties correctly. So note that you use a strict type designation for your instance name, as follows we declare a property to be a private property:

Class privatememberclass{
Private Var privateprop:string= "I am a private property";
}

This private property is named Privatprop. When your instance name is not specified with a strict data type, it may be accessed by the instance.

var instance=new privatememberclass ();
Trace (Instance.privateprop);

The "I am a private property" will be output at this time.

However, if you use a strict data type designation, there will be a compilation error.

Such as:

var instance:privatememberclass=new privatememberclass ();
Trace (Instance.privateprop);

A compilation error occurs at this time. This is a common mistake many people always ask why private properties can be accessed by instances, and now you know.

Dynamic classes allow for the dynamic extension of a class (for example, by allowing new properties or methods to be added). This is called expando in a JScript.NET program, and if a class is not a dynamic class (like the Math Class), users cannot add new properties and methods. In AS1, this is a very common thing. Add new properties and methods to MovieClip as follows:

Movieclip.prototype.somenewmethed=function () {
some methods;
}

This extension is not allowed in AS2. However, I might add new properties and methods by creating subclasses.

The following example is the Max () method in which we want to extend the static class math. We're going to expand it to find the maximum number in some numbers instead of just limiting it to the maximum number of two digits.

Dynamic class Math2 extends Math {
Store a reference to Math.max ()
private static var omax:function = Math.max; Static class cannot be instantiated
Private Function Math2 () {}
Override Math.max (), support any number of arguments
public static function Max (): number {
var a:array = arguments;
var n:number = a.length;
if (n > 2) {
var m:number = OMax (a[n-2],a[n-1]);
Remove two elements from the end of the array;
Could use ' a.length-= 2 ' as a shortcut as
A.pop ();
A.pop ();
A.push (m);
Return number (max.apply (null, a));
else if (n = = 2) {
Return OMax (a[0],a[1]);
else if (n = = 1) {
return a[0];
} else {
return OMax ();
}
}
}

Unlike the original class, we have now extended the Max () method to become a dynamic class. and formed a new class named Math2.

Now you can try it.


Trace (Math2.max (70,6,3,12,82,9,28,5));

ActionScript 2.0--Inheritance

As mentioned earlier. Inheritance is important for OOP programming, although it is not an absolute requirement. It is used to define the relationship between subclasses and super classes. AS2 set a new keyword for this purpose: extends. In the previous example of the Math2 we have used the extends keyword to inherit the math class. It's still quite simple.

The first thing you should notice when you construct a function is the super () closing word. Its role is to invoke the superclass constructor, and if you have not previously constructed a function in the superclass, Flash automatically generates an empty constructor.

Thankfully, many bugs have been fixed in the new Flash player7. However, there are still bugs in FLASHPLAY6, and if you are not sure, you may be able to view related list articles about inherited bugs in AS1.

If you want to pass arguments to your superclass from a subclass, you should make sure that you have a declaration of these parameters in your superclass. Otherwise you will find out why only some of the parameters are passed. If we want to create a subclass named child, it inherits from his parent class. We should write this in the constructor:


Class Child extends Parent {
private var fname:string = "";
Public Function Child (lname:string, fname:string) {
Super (lname);
Continue child ' s constructor code
FName = FName;
}
}

ActionScript 2.0--import of class files outside

For better organization of classes and avoidance of class name conflicts. The concept packages that are applied in many languages are introduced. ActionScript 2.0 introduces packages to solve this problem.

What does a class name conflict mean? We're supposed to have two developers, and everyone has a code base. There is a class named utility in the library. If the two code libraries are used together, this can cause flash chaos, and I don't know which library class to use.

At this point the classpath and come out to save by merging the paths into the class name. Like a file on a hard disk, you can have the same file in a different directory. to indicate which class to reference. To use the correct classpath during the import process.

Import mx.events.Eventdesign;

Once the class is imported, we may be referencing the class with only the class name and not the path to the class.

Class Mybroadcaster {
Public Function Mybroadcaster () {
Eventdesign.initialize (this);
}
}

Of course, you can also specify the correct path to the class at every use, not in the way you import it. But it can be annoying to do so. When you use multiple times, you need to keep typing repetitive things.

Class Mybroadcaster {
Public Function Mybroadcaster () {
Mx.events.EventDesign.initialize (this);
}
}

When creating your own class, place your class in a specified project directory, or in a common class library, rather than placing it in the

<flash install Folder>\<language>\first run\classes\) or <drive>:\documents and Settings\<user >\local Settings\Application Data\Macromedia\Flash MX 2004\<language>\configuration\classes\).

Doing so can reduce the occurrence of compile-time errors at the same time. A common method is to use your negative domain name as the path of the class

Import Com.quantumwave.alliance.rebel.Commander;

If you want to import all the classes in the path. Use the wildcard character *, as follows:

Import com.quantumwave.*

This step imports all the classes under Com.quantumwave but compiles only the classes that are used at compile time, so you don't have to worry about importing all the classes to increase the size of your files.

ActionScript 2.0--Interface

When using OOP, in addition to inheritance is more important, in the interface. Just as Java and c#,actionscript do not provide multiple inheritance (such as a subclass can inherit multiple superclass), This is because if used improperly, it will be like having a nightmare when debugging. It can cause dead loops and sticky situations, and when you design your project, you use an interface to achieve multiple inheritance, without the hassle of saying it.

An interface is like a variety of protocols in the execution of a method, and it is usually not associated with methods that are not executed by each class. There is no code in an interface without attributes, only methods, which are written in exactly the same way as a class, except:

1. None of them have attributes.

2. They only have methods of marking, parameters, types and types of return

3. At the end of the method definition, there are only parentheses and no curly braces.

The following is an example of a dragged class named Dragable (usually beginning with an uppercase "I" when naming an interface).

Interface Idraggable {
Public Function StartDrag (): Void;
Public Function Stopdrag (): Void;
Public Function isdragging (): Boolean;
}

If you want to use interface you need to use the keyword implement. As in the following example, the child class inherits the superclass and uses the interface idraggable.

Class Child extends Parent implements Idraggable {
Public Function Child () {
Add child Constructor Code
}
Public Function StartDrag (): Void {
Implement the Code for StartDrag ();
}
Public Function Stopdrag (): Void {
Implement the Code for Stopdrag ();
}
Public Function isdragging (): Boolean {
Implement the Code for Isdragging ();
}
}

The only thing to be aware of when using interfaces is that in a class, you should use the same method as in the interface, the definition of the parameter type, in which the interface can standardize code between two different programmers, and when a known interface is used by a class, and the order clerk only needs to know the interface to be used in separate classes.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.