O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required