03.05.2013 Views

FLASH® LITE™ 2.x - Adobe Help and Support

FLASH® LITE™ 2.x - Adobe Help and Support

FLASH® LITE™ 2.x - Adobe Help and Support

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example<br />

In the following example, an object has two internal methods, setQuantity() <strong>and</strong><br />

getQuantity(). A property, bookcount, can be used to invoke these methods when it is<br />

either set or retrieved. A third internal method, getTitle(), returns a read-only value that is<br />

associated with the property bookname. When a script retrieves the value of<br />

myBook.bookcount, the ActionScript interpreter automatically invokes<br />

myBook.getQuantity(). When a script modifies the value of myBook.bookcount, the<br />

interpreter invokes myObject.setQuantity(). The bookname property does not specify a<br />

set function, so attempts to modify bookname are ignored.<br />

function Book() {<br />

this.setQuantity = function(numBooks:Number):Void {<br />

this.books = numBooks;<br />

};<br />

this.getQuantity = function():Number {<br />

return this.books;<br />

};<br />

this.getTitle = function():String {<br />

return "Catcher in the Rye";<br />

};<br />

this.addProperty("bookcount", this.getQuantity, this.setQuantity);<br />

this.addProperty("bookname", this.getTitle, null);<br />

}<br />

var myBook = new Book();<br />

myBook.bookcount = 5;<br />

trace("You ordered "+myBook.bookcount+" copies of "+myBook.bookname);<br />

// output: You ordered 5 copies of Catcher in the Rye<br />

The previous example works, but the properties bookcount <strong>and</strong> bookname are added to every<br />

instance of the Book object, which requires having two properties for every instance of the<br />

object. If there are many properties, such as bookcount <strong>and</strong> bookname, in a class, they could<br />

consume a great deal of memory. Instead, you can add the properties to Book.prototype so<br />

that the bookcount <strong>and</strong> bookname properties exist only in one place. The effect, however, is<br />

the same as that of the code in the example that added bookcount <strong>and</strong> bookname directly to<br />

every instance. If an attempt is made to access either property in a Book instance, the<br />

property's absence will cause the prototype chain to be ascended until the versions defined in<br />

Book.prototype are encountered. The following example shows how to add the properties to<br />

Book.prototype:<br />

function Book() {}<br />

Book.prototype.setQuantity = function(numBooks:Number):Void {<br />

this.books = numBooks;<br />

};<br />

Book.prototype.getQuantity = function():Number {<br />

return this.books;<br />

};<br />

522 ActionScript classes

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!