2

我正在使用一个值对象,它可以在实例化时接收对象,因此可以在创建新 VO 时直接更新其默认值,如下所示:

public class SeatSettingsVO
{
    public var globalPosition:Point = new Point(0, 0);
    public var dealerChipOffset:Point = new Point(0, 0);
    public var chipStackOffset:Point = new Point(0, 0);

    public function SeatSettingsVO(obj:Object = null)
    {
        if (obj)
            parseSettings(obj);
    }
}

parseSettings方法使用try/catch块来仅获取传递给构造函数的对象中的现有属性(或者至少,这是意图):

    private function parseSettings(obj:Object):void
    {
        try
        {
            this.globalPosition = obj.globalPosition;
            this.chipStackOffset = obj.chipStackOffset;
            this.dealerChipOffset = obj.dealerChipOffset;
        }
        catch (error:Error)
        {
        }
    }

现在考虑这种情况:需要创建一个新的值对象,但只定义了三个属性之一:

new SeatSettingsVO({globalPosition:new Point(300, 277)})

问题在于,如果obj不包含特定属性(例如chipStackOffset),则该方法不会保持初始属性值(Point(0,0)),而是将其覆盖为null

我的猜测是,访问 Object 类实例上不存在的属性不会触发错误,而是null会返回,这反过来会导致默认值被覆盖。谁能解释这种行为,并可能提出解决方案?

非常感谢。

4

4 回答 4

3

比其他更简洁的解决方案:

this.globalPosition = obj.globalPosition || DEFAULT_GLOBAL_POSITION;

就像在 Python 中一样,|| 如果该操作数的计算结果为 0、null、false、NaN、"" 或 undefined 以外的值,则运算符返回第一个操作数。否则,它按原样返回第二个操作数:

trace(new Point(3, 3) || "hi"); //(x=3, y=3)
trace(false || "hi"); //hi
trace("hi" || "bye"); //hi
trace(0 || null); //null
trace(NaN || 0); //0
trace("" || undefined); //undefined
trace(undefined || new Point(0.4, 0)); //(x=0.4, y=0)
trace(null || false); //false

因此,您可以使用它来检查是否定义了一个值,如果是,则使用该值,如果没有,则使用默认值。老实说,我不确定它是否使您的代码更具可读性,但这是一种选择。

于 2012-05-03T19:52:36.553 回答
2

在这种情况下,您的对象是动态的,因此如果该属性不存在,您不会收到异常。但是,您确实得到undefined. undefined计算结果为 null,所以你总是可以说:

this.globalPosition = obj.globalPosition ? obj.globalPosition : default;

default你想放在那里的东西在哪里......如果你想把它设置回原来的样子,甚至可以this.globalPosition工作。

您还可以询问该属性是否存在:

if( "globalPosition" in obj)
于 2012-05-03T14:44:04.137 回答
2

Flex 对象有一个hasOwnProperty()您可能会觉得有用的方法。您可以使用它来检查动态对象是否定义了参数,并且仅在存在时将其拉出,而不是获取空值。

if (obj.hasOwnProperty("globalPosition"))
    this.globalPosition = obj.globalPosition;
//etc...
于 2012-05-03T14:34:43.643 回答
0
    private function parseSettings(obj:Object):void
    {
        try
        {
            this.globalPosition = obj.globalPosition;
            this.chipStackOffset = obj.chipStackOffset;// when error occured here,
            // this.chipStackOffset still waiting for a value to set and it sets to null.
            // probably dealerChipOffset doesnt change by default value.
            this.dealerChipOffset = obj.dealerChipOffset; // this is {0,0} point prob,didnt try it.
        }
        catch (error:Error)
        {
        }
    }

我会使用类似下面的东西。希望能帮助到你。

    private function parseSettings(obj:Object):void
    {
       for(var name in obj){
            this[name] = obj[name];
       }
    }
于 2012-05-03T14:49:27.917 回答