0

伙计们,我有一个关于向 Flex 中的现有对象添加额外的名称-值对的问题;

我有一个对象类型的 object1,我声明了一个新的 object2 = object1 加上一些额外的名称-值对,有没有办法将新的名称-值对附加到现有对象?

非常感谢,

4

1 回答 1

0

如果我正确理解您的问题,object2 是指向 object1 的引用指针;因此,对 object2 的更改会影响 object1:

package
{
    import flash.display.Sprite;

    public class X extends Sprite
    {
        public function X()
        {
            var object1:Object = {a: "1", b: "2"};

            var object2:Object = object1;

            object2.c = 3;

            trace("Object 2:");
            for (var name:String in object2)
            {
                trace("Name: " + name + " = " + object2[name]);
            }

            trace("Object 1:");
            for (var name:String in object1)
            {
                trace("Name: " + name + " = " + object1[name]);
            }
        }
    }
}

...输出:

Object 2:
Name: a = 1
Name: c = 3
Name: b = 2
Object 1:
Name: a = 1
Name: c = 3
Name: b = 2

如果您询问是否可以克隆对象或动态类,您可以使用如下函数:

public function cloneObject(object:Object):Object
{
    var newObject:Object = {};

    for (var name:String in object)
    {
        newObject[name] = object[name];
    }

    return newObject;
}
于 2012-04-05T20:00:38.813 回答