C# 3 STYLE OBJECT INITIALIZERS IN AS3Sep 22, 2008

Suppose you need to set some properties for a class instance. You would normally do it like this:

var person : Person = new Person();
person.name = "Vladimir";
person.age = 20;

When the number of properties increases this can become quite redundant. In my previous post I used the with keyword which can lead to less bloated code in this situation. Here is another way to initialize an object in a clean way, very similar to the C# object initializers introduced in version 3 of the language. You can achieve this by adding just one line of code in your constructor:

public class Person {

public var name : String;
public var age : int;

public function Person( data : Object ) {
for( var prop : String in data ) this[prop] = data[prop];
}
}
Now we can instantiate the class in this way:
var person : Person = new Person( {name: "Vladimir", age: 20} );
You may have problems implementing this if you are already using the constructor because, ufortunately, ActionScript 3 doesn't support method overloading. A simple solution is to add a static function in the Person class:
public static function create(  data : Object = null ) : Person {
var person : Person = new Person();
for( var prop : String in data ) person[prop] = data[prop];

return person;
}
Now we have:
var person : Person = Person.create( {name: "Vladimir", age: 20} );


Post A Comment

To post comments, please log in or register.

Textback theme designed by Amy & Pink