O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required