在AS3中使用括号语法调用构造函数

时间:2015-03-30 07:37:57

标签: actionscript-3

如您所知,您可以通过两种方式访问​​属性和方法:

dot syntax: object.property=value;  

&安培;

bracket syntax: object["property"]=value; or object["property"]=["value];

括号语法也适用于方法:

this["myMC"]["stop"]();

我试图用构造函数来做到这一点,并且我失败了#34; :(

我尝试制作变量但是 此代码不起作用:

this["mySprite"]=new ["Sprite"](); Error:Instantiation attempted on a non-constructor.

this["mySprite"]=new ["Sprite()"]; Error:Instantiation attempted on a non-constructor.  

this["mySprite"]=["new Sprite"](); Error:Value is not a function.

this["mySprite"]=["new Sprite()"]; Error:a term is undefined and has no properties

他们都没有工作

也许你想知道我为什么要那样:

我想在运行时创建新变量:

this[tf1.text]=new [tf2.text]();

tf1.text是我的变量名,而tf2.text是我的构造函数 然后我在运行时设置我的变量的属性和方法(你知道如何)。

我感谢有用的答案。

1 个答案:

答案 0 :(得分:0)

您可以使用getDefinitionByName()从字符串中获取类,然后从该类创建一个新对象。

这是从字符串中获取Sprite类的示例。

import flash.utils.getDefinitionByName;

var aClass:Class = getDefinitionByName("flash.display.Sprite") as Class;
var sprite:Sprite = new aClass();