Search code examples
flashactionscript-3object-literal

Object literal with constants as keys (in key value pair)


I have a class that holds some constants and will receive an object literal (associative array) with some data like this:

var ConfigObj:Config = new Config({
    "Some" : 10,
    "Other" : 3,
    "Another" : 5
});

The class looks like this:

public dynamic class Config
{
    static public const SomeProperty:String = "Some";
    static public const OtherProperty:String = "OtherProperty";
    static public const AnotherProperty:String = "AnotherProperty";

    public function Config(settings:Object)
    {
        // Doing some stuff here
    }
}

The problem is, how can I pass the constants as keys like this:

var ConfigObj:Config = new Config({
    Config.SomeProperty : 10,
    Config.OtherProperty : 3,
    Config.AnotherProperty : 5
});

Besides, I would like to keep it inline, if possible.

var MyObj:MyClass = new MyClass({x:1, y:2, z:3});

is, for me, far better than:

var Temp:Object = new Object();
Temp.x = 1; // Or Temp[x] = 1;
Temp.y = 2; // Or Temp[y] = 2;
Temp.z = 3; // Or Temp[z] = 3;

var MyObj:MyClass = new MyClass(Temp);

Solution

  • I get the feeling that you're over-complicating your configuration object, however if you do want to use constants to set key-value pairs, you'll need to use a temporary variable:

    var o:Object, configObj:Config;
    o = {};
    o[Config.SomeProperty] = 'foo';
    o[Config.OtherProperty] = 'bar';
    o[Config.AnotherProperty] = 'baz';
    
    configObj = new Config( o );
    

    An important question to ask: are these properties truly constant? If they are, then there's little risk in using the string literal when you instantiate the object:

    new Config( { 'SomeProperty':'foo', 'OtherProperty':'bar', 'AnotherProperty':'baz' } );
    

    Of course, this isn't flexible if the values in the constants change.