O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

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

Get and Set Methods

In the previous section we learned about retriever and modifier methods, which are public methods that retrieve and modify an object's state. Some developers consider such methods cumbersome. They argue that:

pet.setName("Jeff");

is more awkward than:

pet.name = "Jeff";

In our earlier study, we saw that direct variable assignments such as pet.name = "Jeff" aren't ideal object-oriented practice and can lead to invalid variable assignments. To bridge the gap between the convenience of variable assignment and the safety of retriever and modifier methods, ActionScript supports get and set methods. These methods are invoked using variable retrieval- and assignment-syntax.

To define a get method, we use the following general syntax:

function get methodName () {
  statements
}

where the keyword get identifies the method as a get method, methodName is the method's name, and statements is zero or more statements executed when the method is invoked (one of which is expected to return the value associated with methodName).

To define a set method, we use the following general syntax:

function set methodName (newValue) {
  statements
}

where the set keyword identifies the method as a set method, methodName is the method's name, newValue receives the value assigned to an internal instance variable, and statements is zero or more statements executed when the method is invoked. The statements are expected to determine and internally store the value associated with methodName. Note that in ...

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