User Guide

378 Chapter 6: ActionScript Core Classes
You can add getter/setter properties to prototype objects. If you add a getter/setter property to a
prototype object, all object instances that inherit the prototype object inherit the getter/setter
property. This makes it possible to add a getter/setter property in one location, the prototype
object, and have it propagate to all instances of a class (similar to adding methods to prototype
objects). If a get/set function is invoked for a getter/setter property in an inherited prototype
object, the reference passed to the get/set function is the originally referenced object—not the
prototype object.
If invoked incorrectly,
Object.addProperty() can fail with an error. The following table
describes errors that can occur:
Example
In the following example, an object has two internal methods, setQuantity() and
getQuantity(). A property, bookcount, can be used to invoke these methods when it is either
set or retrieved. A third internal method,
getTitle(), returns a read-only value that is associated
with the property
bookname. When a script retrieves the value of myBook.bookcount, the
ActionScript interpreter automatically invokes
myBook.getQuantity(). When a script modifies
the value of
myBook.bookcount, the interpreter invokes myObject.setQuantity(). The
bookname property does not specify a set function, so attempts to modify bookname are ignored.
function Book() {
this.setQuantity = function(numBooks:Number):Void {
this.books = numBooks;
};
this.getQuantity = function():Number {
return this.books;
};
this.getTitle = function():String {
return "Catcher in the Rye";
};
this.addProperty("bookcount", this.getQuantity, this.setQuantity);
this.addProperty("bookname", this.getTitle, null);
}
var myBook = new Book();
myBook.bookcount = 5;
trace("You ordered "+myBook.bookcount+" copies of "+myBook.bookname);
// output: You ordered 5 copies of Catcher in the Rye
Error condition What happens
prop is not a valid property name; for example, an
empty string.
Returns false and the property is not added.
getFunc is not a valid function object. Returns false and the property is not added.
setFunc is not a valid function object. Returns false and the property is not added.