12.6. Creating Smart Getter/Setter Properties

Problem

You want to create a class property on which you can perform calculations before setting or returning a value.

Solution

Use the addProperty( ) method.

Discussion

You can create what are called getter/setter properties for classes using the addProperty( ) method within the class’s constructor. Getter/setter properties are accessed from object instances just like any other properties, but they secretly invoke methods rather than directly accessing an actual property of the same name. This allows your properties to be “smart”—you can perform calculations on the fly rather than just assigning or retrieving a simple value.

To create a getter/setter property, first create getter and setter methods for the class. The getter method should not require any parameters and should return a value. The setter method should take a single parameter and not return any value. By convention, the getter and setter methods are named get PropertyName ( ) and set PropertyName ( ), where PropertyName is the name of the property name they control (with the first letter capitalized).

The addProperty( ) method creates a new property with the name you specify in the first parameter. The second and third parameters passed to addProperty( ) specify the getter and setter methods. It is important that you do not include the parentheses as part of the getter and setter method names when you pass them to the addProperty( ) method (i.e., methodName( ) is wrong, and ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.