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

call constructors by using bracket syntax in AS3

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

dot syntax: object.property=value;  

&

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

括号语法也适用于方法:

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

我试着用构造函数来做,我 "Failed" :(

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

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

None 其中

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

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

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

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

感谢有用的答案。

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

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

import flash.utils.getDefinitionByName;

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