Object Initializers and Fixtures for ECMAScript 4th Edition
A recently released ECMAScript 4 draft specification for object initializers includes significant enhancements to the expressive power of object initializers. This post focuses on the ability to designate specific properties as fixtures, which is not possible in ECMAScript 3rd edition or ActionScript 3.0.
You may have used object initializers in ActionScript 3.0 before. They provide an easy way to assign a literal value to a variable of type Object. For example, in ActionScript 3.0, you may see something like:
This creates an object called myObj with two dynamic properties, name and color. The properties are dynamic in that they are not defined as part of the Object class and can be deleted at runtime. For example, the following code deletes the name property:
In ActionScript 3.0, if you want to ensure that the name property cannot be deleted at runtime, you have to define a class and make name a member, or "trait", of that class. In ActionScript 3.0, a trait is a class member that cannot be deleted at runtime. In ECMAScript 4, traits are called "fixtures", but you don't have to create a class definition to create a fixture. In fact, you can create fixtures with object initializers. For example, let's say you want to make the name property a fixture, so that runtime code cannot delete the property. In ES4, you'll be able to do this:
What if you want both name and color to be fixtures? All you have to do is place the "var" keyword before the curly braces. Doing so will make every property you name a fixture, like so:
The fun doesn't stop there, though. Let's say you like creating objects on the fly like this, but that you'd want each object to have a unique ID number property that not only is a fixture, but also is a constant (i.e. read-only). All you have to do is use the keyword const instead of var:
You can also use the const keyword before the curly braces if you want to make all of the properties you name read-only fixtures.
Here's a list of relevant links:
- Draft 3 of the Object Initializer specification posted by Lars Hansen on ES4-Discuss
- Lars Hansen post on ES4-Discuss about first draft of Object Initializers spec
- Lars Hansen post on ES4-Discuss about second draft of Object Initializers spec
- Lars Hansen post on ES4-Discuss about third draft of Object Initializers spec