`

AS3.0 Dynamic class

阅读更多

In Java, if you’ve created an object from a particular class, you can use only properties and methods that were defined in this class. For example, if the following class:

class Person {
String name;
}

you can only manipulate with the name property:

Person p = new Person();
p.name = “Joe”;
System.out.println(p.name);

ActionScript calls such classes sealed, but it also has different animals: dynamic classes, which allow you to programmatically add new properties and behavior to classes during the run-time. Just add the magic keyword dynamic to the class definition:

dynamic class Person {
var name:String;
}

Now let’s add dynamically two variables name and age and the function printme() to the object of type Person:

Person p= new Person();
p.name=”Joe”;
p.age=25;
p.printMe = function () {
trace (p.name, p.age);
}
p.printMe(); // Joe 25

You do not have complete freedom though: you can dynamically add only public properties and methods. Of course, nothing comes for free and sealed classes are a bit more efficient in terms of memory consumption, because they do not need to create a hash table to store the properties and methods that are unknown during compilation. Another obvious restriction is that dynamically added functions can’t access private members of the dynamic class. Read the article Programming In Style or an Elevator Pitch to see how by just declaring standard Flex component dynamic, the your code becomes more simple and elegant.

In AS3, any function can be attached to a dynamically created property of a dynamic object, for example

function calcTax():Number {…}

var myObject:SomeObject = new SomeObject();
myObject.tax=calcTax; //add the tax property and attach the function calcTax()
var myTax=myObject.tax();

The delete operator destroys the property of an object and makes it eligible for garbage collection:

delete calcTax();
myTax=myObject.tax() // generates an error

Some of the Flex classes were defined as dynamic, i.e. Object, Array, MovieClip, NetConnection, TextField, and others. At the time of this writing, subclasses of dynamic classes are not dynamic by default.
Because of this, you may run into an ugly run-time error: imagine a sealed class S that extends a dynamic class D. If you create an object as
D myObj = new S(), an attempt to add a propery to myObj will produce a runtime error because the variable myObj points at a sealed object.

Let’s do a quick test. Create a new project in FlexBuilder and select ActionScript project as its type. Enter AS_Only_Project as the project name. In a couple of seconds you’ll see the auto-generated code that looks as follows:

package {
import flash.display.Sprite;

public class AS_Only_Project extends Sprite
{
public function AS_Only_Project()
{
}
}
}

Next, create a new class called D and check odd the Dynamic checkbox in FlexBuilder pop-up. You’ll get this class.

package {
public dynamic class D
{
}
}

Now, instantiate and test the dynamic nature of the class D by adding the constructor
public function AS_Only_Project()
{
var myD:D=new D();
myD.favoriteBand=”Pink Floyd”;
trace(”Favorite Band=”+myD.favoriteBand);
}
Run this application in the debug mode, and sure enough it’ll print

Favorite Band=Pink Floyd

Create one more sealed class called S inherited from the dynamic D:
package {
public class S extends D
{
}
}

An attempt to add properties on the fly to the instance of the class S fails miserably as expected:

var myS:D = new S();
myS.favoriteSinger=”Alla Pugacheva”;
trace(”Favorite Singer=”+myS.favoriteSinger);

ReferenceError: Error #1056: Cannot create property favoriteSinger on S.
at AS_Only_Project$iinit()[C:\TheRIABook\eclipse\AS_Only_Project\AS_Only_Project.as:13]

If you’ll try to instantiate your sealed class as follows:

var myS:D = new S() as D;

I have two news for you: the good news is that it compiles, and the bad (and expected) news is that it generates exactly the same runtime error.

Most likely Adobe’s gonna hire a hitman and kill me after the following statement, but I’m going to say it anyway (at least you’ll now who to blame)… May be I should not?…Life is so good, and I’d like to witness the success of Apollo…I’m sayyyiiiinng this:

If you need to add new functionality to one of the existing standard Flex components (buttons, comboboxes and the like), do not bother extending them and creating new classes. Just create one simple empty subclass with the keyword dynamic and instantiate and add new properties on the fly as needed, as was shown by the Smalltalk student in this article.

A sound of a silenced pistol shot. Curtain.

Yakov Fain

o-link : 

分享到:
评论

相关推荐

    AS3.0的关键字和保留字

    ### AS3.0的关键字和保留字 #### 一、概述 ActionScript 3.0(简称AS3.0)是一种广泛应用于Flash平台的强类型面向对象编程语言。它不仅支持传统的面向过程编程,还提供了丰富的面向对象特性,使得开发者能够创建...

    ActionScript3.0教程

    ActionScript 3.0(以下简称AS3)是Adobe公司在发布Flash Player 9时引入的一种全新的脚本语言。相比于之前的ActionScript 2.0(以下简称AS2),AS3在语法结构、性能优化以及面向对象编程方面都有了显著的进步。 - ...

    FLASH As3_basic 入门源码

    【标题】"FLASH As3_basic 入门源码"揭示了这个压缩包是关于Adobe Flash平台中ActionScript 3.0(简称AS3)的基础学习资源。ActionScript是一种面向对象的编程语言,广泛用于创建交互式的动画、游戏以及富互联网应用...

    Mybatis实例——可直接导入eclipse运行

    1. **创建项目**:在Eclipse中,选择`File -> New -> Dynamic Web Project`,输入项目名称,例如"MybatisDemo",并按照向导设置项目的其他属性。 2. **导入Mybatis库**:在项目中,右键点击`WebContent/WEB-INF/lib...

    Eclipse创建最简单的struts2项目

    在Eclipse中,选择"File" -> "New" -> "Dynamic Web Project",输入项目名称,比如"SimpleStruts2Project",选择Web项目版本(通常选择与Tomcat版本匹配的版本,例如3.0或3.1),并确保"Generate web.xml deployment...

    Windows Presentation Foundation Unleashed (2007).rar

    <br>Windows Presentation Foundation (WPF) is a key component of the .NET Framework 3.0, giving you the power to create richer and more compelling applications than you dreamed possible. Whether ...

    stdafx.h代码

    // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for ...

    Servlet Hellowword

    1. **创建Web项目**:打开MyEclipse,选择“File” -> “New” -> “Dynamic Web Project”,输入项目名称(如:firstweb),选择JRE版本,点击“Finish”。 2. **添加Servlet**:右键点击项目,选择“New” -> ...

    用MyEclipse建立Struts图解

    3. **配置项目属性**:在“Dynamic Web Module”选项卡中,设置Web模块版本(通常选择3.0或以上),并在“Target Runtime”中选择你的服务器环境,如Tomcat。点击“Finish”创建项目。 4. **添加Struts库**:右键...

    Professional.MFC.with.VC6

    Chapter 12: Creating Dynamic-link Libraries Libraries Dynamic-link Libraries Architectural Decisions Initializing a DLL Coding with DLLs A Bit of History Building A DLL Easing the Build Process...

    flash 中实现打字效果的一个方法

    在“Typewriter”类的AS3文件中(例如:Typewriter.as),编写以下代码: ```actionscript import flash.events.Event; public class Typewriter extends MovieClip { private var _textToType:String; private ...

    VB编程资源大全(英文源码 数据库)

    <END><br>51,Dynarep.zip This program generates a dynamic datareport during runtime without using any DataEnvironment object. I have passed the datasource and recordset properties during run time. ...

    使用Eclipse构建Maven的Web项目用jetty启动.docx

    2. **修改 class 路径**:为了确保编译后的 `.class` 文件正确地放置到指定位置,需要修改项目的构建路径。右键点击项目,选择 `Java Build Path` -> `Source`。在弹出的对话框中,可以看到四个文件夹:`src/main/...

    simple-tags

    * Remove tags as HTML keywords * Remove nofollow options * Remove custom function for display current post tags * Remove auto-add post tags * Remove embedded tags * Change method for tags for ...

    ssm环境搭建

    1. 在Eclipse中选择"File" > "New" > "Dynamic Web Project",输入项目名称,选择动态Web模块版本(通常为3.0或以上),并确认。 2. 在项目属性中,选择"Maven",勾选"Use Maven Nature",然后点击"Configure"配置...

    Hibernate 中文 html 帮助文档

    1.2.1. 第一个class 1.2.2. 映射文件 1.2.3. Hibernate配置 1.2.4. 用Ant构建 1.2.5. 启动和辅助类 1.2.6. 加载并存储对象 1.3. 第二部分 - 关联映射 1.3.1. 映射Person类 1.3.2. 单向Set-based的关联 ...

    python3.6.5参考手册 chm

    PEP 487: Simpler customization of class creation PEP 487: Descriptor Protocol Enhancements PEP 519: Adding a file system path protocol PEP 495: Local Time Disambiguation PEP 529: Change Windows ...

Global site tag (gtag.js) - Google Analytics