Suppose you need to set some properties for a class instance. You would normally do it like this:
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:var person : Person = new Person();
person.name = "Vladimir";
person.age = 20;
Now we can instantiate the class in this way:
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];
}
}
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:
var person : Person = new Person( {name: "Vladimir", age: 20} );
Now we have:
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;
}var person : Person = Person.create( {name: "Vladimir", age: 20} );
Latest Comments