July 2003
Intermediate to advanced
896 pages
45h 43m
English
You want to create a read-only property for a class.
Use the addProperty( ) method in the constructor
and pass it a null value for the setter method.
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 is getVersion( ). The setter method is null.
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 is getArea( ). The setter method is null. 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 ...Read now
Unlock full access