12.7. Defining Read-Only Properties
Problem
You want to create a read-only property for a class.
Solution
Use the addProperty( )
method in the constructor
and pass it a null
value for the setter method.
Discussion
There are at least two good reasons to have read-only properties:
You want to create constants for your class.
You want to have a dependent property whose value depends on other properties/factors.
The addProperty( )
method creates getter/setter
properties for a class. Passing addProperty( )
a
null
value for the setter method parameter
effectively creates a read-only property.
See Recipe 12.6 for the initial implementation of the Square class. Here is a modified version:
_global.Square = function (side) { this.side = side; // Create a read-only property,version
(effectively, a constant). The getter // method isgetVersion( )
. The setter method isnull
. this.addProperty("version", this.getVersion, null); // Create a dependent property,area
(its value changes, so it is not a constant, // but the value depends on other property values and can't be set directly). The // getter method isgetArea( )
. The setter method isnull
. this.addProperty("area", this.getArea, null); }; Square.prototype.getArea = function ( ) { return Math.pow(this.side, 2); }; Square.prototype.getVersion = function ( ) { // Always returns the string "1.0". Therefore, it is a constant. return "1.0"; }; // Create a square with a side length of 5. sq = new Square(5); trace(sq.area); // Displays: 25 // Try to set ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.