通过在AS3字符串访问属性 [英] Accessing properties via a String in AS3

查看:437
本文介绍了通过在AS3字符串访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个引擎,我创建了一段时间后,加载对象转换成基于XML数据的容器。该XML的一个非常简单的例子是这样的:

I have an engine I created a while back that loads objects into a container based on XML data. A really quick example of the XML would be like this:

<level>
    <object cname="enemies.Robot">
        <pos x="200" y="400" layer="mobiles" />
    </object>
    <object cname="Player">
        <pos x="12" y="89" layer="mobiles" />
    </object>
</level>

我有一个类的环保,有一个方法 loadLevel(数据:XML)这是我通过解析XML,那么该函数通过XML运行找出所有的对象节点和用途 getDefinitionByName ,以确定哪个对象我想根据要创建的对象。@ CNAME

I have a class Environment that has a method loadLevel(data:XML) which I parse the XML through, then the function runs through the XML finding all object nodes and uses getDefinitionByName to determine which Object I want to create based on object.@cname.

在这里,我有一个基于像这样的XML手动定义每个属性;

From here, I have to manually define each property based on the XML like so;

obj.x = xml.pos.@x;
obj.y = xml.pos.@y;

等。

我在想,如果有一个用于设置基于字符串的属性一个内置的方法。我的意思是像这样:

I was wondering if there's an inbuilt method for setting a property based on a String. By this I mean something like so:

var mc:MovieClip = new MovieClip();
mc.someInbuiltFunctionThatSetsAProperty("alpha", 0.5);

这样我可以改变我的XML更象这样:

This way I could change my XML to be more like so:

<object cname="Player">
    <props>
        <x>200</x>
        <y>221</y>
        <alpha>7834</alpha>

        <health>Something</health>
        <power>3</power>
    </props>
</object>

和遍历道具设置我所有的性能上飞。

And iterate through all the children of props to set all of my properties on the fly.

我知道,如果我创建一个对象并设置在其中,像这样的属性:

I know if I create an Object and set properties within it like so:

var obj:Object = 
{
    var1: "hello",
    var2: "there",
    name: "marty"
};

您可以通过名称/值,然后使用迭代的的(字符串对象)循环是这样的:

var i:String;
for(i in obj)
{
    trace(i + ": " + obj[i]);
}

/**
 * Output:
 * var1: hello
 * var2: there
 * name: marty
 */

有可能的东西,甚至类似于?

Is there maybe something even similar to that?

当然,还有一种方式,因为这里是确定使用字符串属性的例子:

Surely there's a way, as here's an example of identifying a property using a String:

var ar:Array = [new MovieClip(), new MovieClip()];
ar.sortOn("alpha", Array.ASCENDING);

所以,只是为了让我的问题更多了点:我希望能够获取和设置,我可以用一个字符串识别性能

So just to make my question more to-the-point: I want to be able to get and set properties that I can identify using a String.

推荐答案

为什么不使用 [字符串属性] 注释:

var mc:MovieClip=new MovieClip()
mc["alpha"] = 0.5            // setter
var alpha:Number=mc["alpha"] // getter

这篇关于通过在AS3字符串访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆