User Guide

Object.addProperty() 663
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
The previous example works, but the properties bookcount and bookname are added to every
instance of the
Book object, which requires having two properties for every instance of the object.
If there are many properties, such as
bookcount and bookname, in a class, they could consume a
great deal of memory. Instead, you can add the properties to
Book.prototype so that the
bookcount and bookname properties exist only in one place. The effect, however, is the same as
that of the code in the example that added
bookcount and bookname directly to every instance. If
an attempt is made to access either property in a Book instance, the property’s absence will cause
the prototype chain to be ascended until the versions defined in
Book.prototype are
encountered. The following example shows how to add the properties to
Book.prototype:
function Book() {}
Book.prototype.setQuantity = function(numBooks:Number):Void {
this.books = numBooks;
};
Book.prototype.getQuantity = function():Number {
return this.books;
};
Book.prototype.getTitle = function():String {
return "Catcher in the Rye";
};
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.
Error condition What happens